'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
import { BookOpen, AlertTriangle, Menu, ChevronLeft } from 'lucide-react';

interface Lesson {
  id: number; title: string; content?: string; sortOrder: number; status: string;
}
interface Chapter {
  id: number; title: string; sortOrder: number; lessons: Lesson[];
}
interface Course {
  id: number; title: string; description: string; cover?: string;
  isFree: boolean; price: number; status: string;
  category?: { name: string };
  chapters: Chapter[];
  createdAt: string;
}

function LoadingSkeleton() {
  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-6" />
      <Skeleton className="h-4 w-32 mb-8" />
      <Skeleton className="h-64 w-full mb-4 rounded-xl" />
      <Skeleton className="h-4 w-full mb-2" />
      <Skeleton className="h-4 w-3/4" />
    </div>
  );
}

export default function CourseDetailClient() {
  const params = useParams();
  const [course, setCourse] = useState<Course | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeLesson, setActiveLesson] = useState<Lesson | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(true);

  useEffect(() => {
    if (!params.id) return;
    setLoading(true);
    fetch(`${API_BASE}/courses/${params.id}`)
      .then(r => r.json())
      .then(data => {
        if (!data || !data.id) throw new Error('课程不存在');
        setCourse(data);
        const firstLesson = data.chapters?.[0]?.lessons?.[0];
        if (firstLesson) setActiveLesson(firstLesson);
      })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, [params.id]);

  if (loading) return <LoadingSkeleton />;

  if (error || !course) return (
    <div className="max-w-3xl mx-auto px-4 py-20 text-center">
      <div className="w-16 h-16 bg-destructive/10 rounded-2xl flex items-center justify-center mx-auto mb-4">
        <AlertTriangle className="w-8 h-8 text-destructive" />
      </div>
      <h1 className="text-xl font-bold text-foreground mb-2">{error || '课程不存在'}</h1>
      <Link href="/courses" className="text-brand-600 hover:underline text-sm">返回课程列表</Link>
    </div>
  );

  const totalLessons = course.chapters.reduce((sum, ch) => sum + ch.lessons.length, 0);

  return (
    <>

      <div className="flex h-[calc(100vh-4rem)] max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Sidebar */}
        <aside className={`
          ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}
          fixed md:relative md:translate-x-0 z-30
          w-72 bg-card border-r border-border
          overflow-y-auto flex-shrink-0 transition-transform
        `}>
          <div className="p-4 border-b border-border">
            <Link href="/courses" className="text-xs text-muted-foreground hover:text-brand-600 mb-2 inline-flex items-center gap-1">
              <ChevronLeft className="w-3 h-3" />
              返回课程列表
            </Link>
            <h2 className="font-semibold text-foreground text-sm line-clamp-2 mt-2">{course.title}</h2>
            <p className="text-xs text-muted-foreground mt-1">
              <BookOpen className="w-3 h-3 inline mr-1 align-text-bottom" />
              {course.chapters.length} 章 · {totalLessons} 课时
            </p>
          </div>

          <nav className="p-2">
            {course.chapters.map((chapter, ci) => (
              <div key={chapter.id} className="mb-3">
                <div className="text-xs font-medium text-muted-foreground px-2 py-1.5">
                  {ci + 1}. {chapter.title}
                </div>
                {chapter.lessons.map((lesson, li) => (
                  <button
                    key={lesson.id}
                    onClick={() => setActiveLesson(lesson)}
                    className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
                      activeLesson?.id === lesson.id
                        ? 'bg-brand-50 text-brand-700 dark:bg-brand-950/30 dark:text-brand-400 font-medium'
                        : 'text-muted-foreground hover:bg-muted/50'
                    }`}
                  >
                    <span className="text-xs text-muted-foreground mr-2">{ci + 1}.{li + 1}</span>
                    {lesson.title}
                  </button>
                ))}
              </div>
            ))}
            {course.chapters.length === 0 && (
              <p className="text-sm text-muted-foreground text-center py-8">暂无课时内容</p>
            )}
          </nav>
        </aside>

        {/* Mobile overlay */}
        {sidebarOpen && (
          <div className="fixed inset-0 bg-black/20 z-20 md:hidden" onClick={() => setSidebarOpen(false)} />
        )}

        {/* Main content */}
        <div className="flex-1 flex flex-col min-w-0">
          {/* Top bar */}
          <div className="sticky top-0 z-10 bg-card border-b border-border px-4 py-3 flex items-center gap-3">
            <button
              onClick={() => setSidebarOpen(!sidebarOpen)}
              className="md:hidden p-1.5 rounded-lg hover:bg-muted"
              aria-label="切换侧边栏"
            >
              <Menu className="w-5 h-5 text-muted-foreground" />
            </button>

            <div className="flex-1 min-w-0">
              <h1 className="text-sm font-medium text-foreground truncate">
                {activeLesson?.title || course.title}
              </h1>
            </div>

            <div className="flex items-center gap-2 text-xs text-muted-foreground shrink-0">
              <span className="bg-green-100 dark:bg-green-950/30 text-green-700 dark:text-green-400 px-2 py-0.5 rounded font-medium">
                免费
              </span>
              {course.category && (
                <span className="bg-muted px-2 py-0.5 rounded">{course.category.name}</span>
              )}
            </div>
          </div>

          {/* Lesson content */}
          <div className="flex-1 overflow-y-auto">
            {activeLesson ? (
              <article className="max-w-3xl mx-auto px-4 sm:px-6 py-8">
                <h1 className="text-2xl font-bold text-foreground mb-6">{activeLesson.title}</h1>
                <div className="text-card-foreground leading-relaxed whitespace-pre-wrap">
                  {activeLesson.content ? (
                    <div className="space-y-4 [&>h2]:text-lg [&>h2]:font-semibold [&>h2]:text-foreground [&>h2]:mt-8 [&>h2]:mb-3
                      [&>h3]:text-base [&>h3]:font-semibold [&>h3]:text-foreground [&>h3]:mt-6 [&>h3]:mb-2
                      [&>p]:text-muted-foreground [&>p]:leading-relaxed
                      [&>ul]:list-disc [&>ul]:pl-6 [&>ul]:space-y-1 [&>ul]:text-muted-foreground
                      [&>ol]:list-decimal [&>ol]:pl-6 [&>ol]:space-y-1 [&>ol]:text-muted-foreground
                      [&>li]:text-muted-foreground
                      [&>strong]:text-foreground [&>strong]:font-semibold
                      [&>code]:bg-muted [&>code]:px-1.5 [&>code]:py-0.5 [&>code]:rounded [&>code]:text-sm [&>code]:font-mono
                      [&>pre]:bg-muted [&>pre]:p-4 [&>pre]:rounded-xl [&>pre]:overflow-x-auto [&>pre]:text-sm
                    ">
                      {activeLesson.content}
                    </div>
                  ) : (
                    <p className="text-muted-foreground italic">暂无内容</p>
                  )}
                </div>
              </article>
            ) : (
              <div className="flex items-center justify-center h-full">
                <div className="text-center">
                  <div className="w-16 h-16 bg-muted rounded-2xl flex items-center justify-center mx-auto mb-4">
                    <BookOpen className="w-8 h-8 text-muted-foreground" />
                  </div>
                  <p className="text-muted-foreground">请从左侧选择课时开始学习</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}