import { Link, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Award, TrendingUp, BookOpen, Flame, Search } from 'lucide-react';
import { useUserStore } from '../store/useUserStore';
import { useSearchStore } from '../store/useSearchStore';
import { COURSE_DATA } from '../config/courseData';
import { Web3Oracle } from '../components/interactive';
import LanguageSwitcher from '../components/LanguageSwitcher';
import ThemeToggle from '../components/ThemeToggle';
import MobileNav from '../components/MobileNav';
import SeoHead from '../components/SeoHead';
import ProgressExport from '../components/ProgressExport';
import ProgressImport from '../components/ProgressImport';
import { buildSiteUrl } from '../config/siteConfig';

/**
 * 仪表板页面
 * 显示课程列表和学习进度
 */
const DashboardPage = () => {
  const { lang } = useParams();
  const { t } = useTranslation();
  const { totalExperience, userTitle, progress, studyStreak, getLessonProgress } = useUserStore();
  const openSearch = useSearchStore((s) => s.openSearch);

  const progressCount = Object.keys(progress).length;

  const canonicalUrl = buildSiteUrl(`/${lang}/dashboard`);
  const altLang = lang === 'en' ? 'zh' : 'en';
  const alternateUrl = buildSiteUrl(`/${altLang}/dashboard`);

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950">
      <SeoHead
        title={t('dashboard.pageTitle')}
        description={t('dashboard.pageDesc')}
        url={canonicalUrl}
        type="webpage"
        lang={lang}
        alternateUrl={alternateUrl}
      />
      {/* Header */}
      <nav
        aria-label={t('dashboard.navLabel')}
        className="border-b border-slate-200 dark:border-slate-800"
      >
        <div className="container mx-auto px-4 py-4 flex items-center justify-between">
          <Link
            to={`/${lang}`}
            className="flex items-center gap-2 text-slate-500 dark:text-slate-400 hover:text-cyan-400 transition-colors"
          >
            <ArrowLeft className="w-5 h-5" />
            <span>{t('nav.backToHome')}</span>
          </Link>

          <div className="flex items-center gap-4">
            {/* Desktop nav */}
            <div className="hidden sm:flex items-center gap-4">
              <button
                onClick={openSearch}
                aria-label={t('nav.searchCourses')}
                className="flex items-center gap-2 px-3 py-1.5 text-slate-500 hover:text-slate-600 dark:hover:text-slate-300 bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg text-sm transition-colors"
              >
                <Search className="w-4 h-4" />
                <span>{t('nav.searchCourses')}</span>
                <kbd className="ml-1 px-1.5 py-0.5 bg-slate-200 dark:bg-slate-700 rounded text-xs">
                  {t('nav.searchPlaceholder')}
                </kbd>
              </button>
              <Link
                to={`/${lang}/badges`}
                className="flex items-center gap-2 text-slate-500 dark:text-slate-400 hover:text-purple-400 transition-colors"
              >
                <Award className="w-5 h-5" />
                <span>{t('nav.badges')}</span>
              </Link>
              <ThemeToggle />
              <LanguageSwitcher />
            </div>
            {/* Mobile nav */}
            <MobileNav
              items={[
                {
                  label: t('nav.badges'),
                  to: `/${lang}/badges`,
                  icon: <Award className="w-4 h-4" />,
                },
              ]}
              extra={
                <button
                  onClick={openSearch}
                  className="flex items-center gap-3 px-3 py-2 rounded-lg text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800 w-full"
                >
                  <Search className="w-4 h-4" />
                  <span>{t('nav.searchCourses')}</span>
                </button>
              }
            />
          </div>
        </div>
      </nav>

      <main className="container mx-auto px-4 py-8">
        {/* User Stats */}
        <div className="mb-8 p-6 bg-white/60 dark:bg-slate-900/60 backdrop-blur-md border border-slate-200/50 dark:border-slate-700/50 rounded-xl">
          <div className="mb-4 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
            <h2 className="text-2xl font-bold text-slate-900 dark:text-white">
              {t('dashboard.overviewTitle')}
            </h2>
            <div className="flex flex-col gap-3 sm:flex-row sm:items-start">
              <ProgressExport />
              <ProgressImport />
            </div>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-full bg-cyan-500/10 flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-cyan-400" />
              </div>
              <div>
                <p className="text-slate-500 dark:text-slate-400 text-sm">
                  {t('dashboard.statXp')}
                </p>
                <p className="text-slate-900 dark:text-white text-xl font-bold">
                  {totalExperience} XP
                </p>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-full bg-purple-500/10 flex items-center justify-center">
                <Award className="w-6 h-6 text-purple-400" />
              </div>
              <div>
                <p className="text-slate-500 dark:text-slate-400 text-sm">
                  {t('dashboard.statTitle')}
                </p>
                <p className="text-slate-900 dark:text-white text-xl font-bold">{userTitle}</p>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-full bg-blue-500/10 flex items-center justify-center">
                <BookOpen className="w-6 h-6 text-blue-400" />
              </div>
              <div>
                <p className="text-slate-500 dark:text-slate-400 text-sm">
                  {t('dashboard.statCompleted')}
                </p>
                <p className="text-slate-900 dark:text-white text-xl font-bold">{progressCount}</p>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-full bg-orange-500/10 flex items-center justify-center">
                <Flame className="w-6 h-6 text-orange-400" />
              </div>
              <div>
                <p className="text-slate-500 dark:text-slate-400 text-sm">
                  {t('dashboard.statStreak')}
                </p>
                <p className="text-slate-900 dark:text-white text-xl font-bold">
                  {t('dashboard.streakDays', { count: studyStreak })}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Course Modules */}
        <div className="space-y-6">
          {COURSE_DATA.map((module) => {
            const Icon = module.icon;
            const completedCount = module.lessons.filter((lesson) =>
              getLessonProgress(`${module.id}-${lesson.id}`)
            ).length;
            const progressPercent = ((completedCount / module.lessons.length) * 100).toFixed(0);

            return (
              <div
                key={module.id}
                className="p-6 bg-white/60 dark:bg-slate-900/60 backdrop-blur-md border border-slate-200/50 dark:border-slate-700/50 rounded-xl"
              >
                {/* Module Header */}
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div
                      className={`w-12 h-12 rounded-full bg-gradient-to-br ${module.color} flex items-center justify-center`}
                    >
                      <Icon className="w-6 h-6 text-white" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="text-xl font-bold text-slate-900 dark:text-white">
                          {module.title}
                        </h3>
                        {module.id === 'module-7' && (
                          <span className="px-2 py-0.5 text-xs rounded-full bg-rose-500/10 text-rose-400 border border-rose-500/20">
                            🔧 实战模块
                          </span>
                        )}
                      </div>
                      <p className="text-slate-500 dark:text-slate-400">
                        {t('dashboard.lessonsCount', { count: module.lessons.length })}
                      </p>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="text-2xl font-bold text-cyan-400">{progressPercent}%</div>
                    <div className="text-sm text-slate-500 dark:text-slate-400">
                      {completedCount}/{module.lessons.length}
                    </div>
                  </div>
                </div>

                {/* Progress Bar */}
                <div className="mb-4 h-2 bg-slate-200 dark:bg-slate-800 rounded-full overflow-hidden">
                  <div
                    className={`h-full bg-gradient-to-r ${module.color} transition-all duration-500`}
                    style={{ width: `${progressPercent}%` }}
                  />
                </div>

                {/* Lessons */}
                <div className="space-y-2">
                  {module.lessons.map((lesson) => {
                    const isCompleted = getLessonProgress(`${module.id}-${lesson.id}`);
                    return (
                      <Link
                        key={lesson.id}
                        to={`/${lang}/learn/${module.id}/${lesson.id}`}
                        className={`block p-3 sm:p-4 bg-slate-100/40 dark:bg-slate-800/40 border rounded-lg transition-all ${
                          isCompleted
                            ? 'border-green-500/30 bg-green-500/5'
                            : 'border-slate-200/30 dark:border-slate-700/30 hover:border-cyan-500/40 hover:bg-slate-100/60 dark:hover:bg-slate-800/60'
                        }`}
                      >
                        <div className="flex items-center justify-between">
                          <span
                            className={`${isCompleted ? 'text-green-400' : 'text-slate-900 dark:text-white'}`}
                          >
                            {lesson.title}
                          </span>
                          {isCompleted ? (
                            <span className="text-green-400">✓</span>
                          ) : (
                            <span className="text-cyan-400">→</span>
                          )}
                        </div>
                      </Link>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>

        {/* Web3 Oracle */}
        <div className="mt-8">
          <Web3Oracle />
        </div>
      </main>
    </div>
  );
};

export default DashboardPage;
