import { useParams, Link } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { useCourse, useChapters, useGrades, useCourseCompletion } from "@/hooks/queries";
import { ArrowLeft, BookOpen, Lock, ChevronRight, Play, CheckCircle2, Trophy } from "lucide-react";

export default function StudentCourseDetail() {
  const { id } = useParams();
  const courseId = Number(id);
  const { data: course, isLoading: lc } = useCourse(courseId);
  const { data: chapters = [], isLoading: lch } = useChapters(courseId);
  const { data: gradesData, isLoading: lg } = useGrades({ course_id: courseId });
  const { data: completion } = useCourseCompletion(courseId);
  const gradeRecords = gradesData ?? [];
  if (lc || lch || lg) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  if (!course) return <div className="p-8 text-center text-muted-foreground">Course not found.</div>;

  const sortedChapters = [...chapters].sort((a, b) => a.sequence - b.sequence);
  const completedChapters = completion?.chapters_completed ?? 0;
  const progress = completion?.progress_percent ?? (chapters.length > 0 ? Math.round((completedChapters / chapters.length) * 100) : 0);
  const isCompleted = completion?.status === "completed";
  const postTestAvailable = completion?.post_test_available ?? false;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" asChild><Link to="/student/courses"><ArrowLeft className="h-4 w-4 rtl:rotate-180" /></Link></Button>
        <div>
          <h1 className="text-2xl font-bold">{course.title}</h1>
          <p className="text-muted-foreground">{course.code} · {chapters.length} chapters</p>
        </div>
      </div>

      {isCompleted && (
        <Card className="border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-800">
          <CardContent className="pt-6 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Trophy className="h-8 w-8 text-green-600" />
              <div>
                <p className="font-semibold text-green-800 dark:text-green-200">Course Completed!</p>
                <p className="text-sm text-green-600 dark:text-green-400">You've finished all {chapters.length} chapters.</p>
              </div>
            </div>
            {postTestAvailable && (
              <Button asChild>
                <Link to={`/student/my-exams?course_id=${courseId}`}>Take Post-Test</Link>
              </Button>
            )}
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm text-muted-foreground">Overall Progress</span>
            <span className="text-sm font-bold">{progress}%</span>
          </div>
          <Progress value={progress} className="h-3" />
          <p className="text-xs text-muted-foreground mt-2">{completedChapters} of {chapters.length} chapters completed</p>
        </CardContent>
      </Card>

      <Tabs defaultValue="chapters">
        <TabsList>
          <TabsTrigger value="chapters">Chapters ({chapters.length})</TabsTrigger>
          <TabsTrigger value="grades">Grades ({gradeRecords.length})</TabsTrigger>
          <TabsTrigger value="about">About</TabsTrigger>
        </TabsList>

        <TabsContent value="chapters" className="space-y-3 mt-4">
          {sortedChapters.length === 0 ? (
            <div className="text-center py-12">
              <BookOpen className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
              <p className="text-muted-foreground text-sm">No chapters available yet.</p>
            </div>
          ) : sortedChapters.map((ch, idx) => (
            <Link
              key={ch.id}
              to={ch.is_unlocked ? `/student/courses/${courseId}/chapters/${ch.id}` : "#"}
              className={ch.is_unlocked ? "" : "pointer-events-none"}
            >
              <Card className={`transition-shadow ${ch.is_unlocked ? "hover:shadow-md cursor-pointer" : "opacity-60"}`}>
                <CardContent className="flex items-center gap-4 py-4">
                  <div className="flex items-center justify-center h-10 w-10 rounded-full bg-primary/10 text-primary font-bold text-sm shrink-0">
                    {idx + 1}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="font-medium text-sm truncate">{ch.name}</p>
                      {!ch.is_unlocked && <Lock className="h-3 w-3 text-muted-foreground shrink-0" />}
                    </div>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {ch.material_count} materials
                      {ch.description ? ` · ${ch.description.slice(0, 60)}${ch.description.length > 60 ? "..." : ""}` : ""}
                    </p>
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    {ch.is_unlocked ? (
                      <Badge variant="secondary" className="text-xs">
                        <Play className="h-3 w-3 mr-1" /> Open
                      </Badge>
                    ) : (
                      <Badge variant="outline" className="text-xs">Locked</Badge>
                    )}
                    <ChevronRight className="h-4 w-4 text-muted-foreground" />
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </TabsContent>

        <TabsContent value="grades" className="mt-4 space-y-3">
          {gradeRecords.length === 0 ? (
            <p className="text-muted-foreground text-sm text-center py-8">No grades yet for this course.</p>
          ) : gradeRecords.map(g => (
            <div key={g.id} className="flex items-center justify-between p-3 rounded border">
              <div>
                <p className="text-sm font-medium">{g.assignment_title}</p>
                <p className="text-xs text-muted-foreground">{g.date}</p>
              </div>
              <span className="font-bold text-primary">{g.grade}/{g.max_grade}</span>
            </div>
          ))}
        </TabsContent>

        <TabsContent value="about" className="mt-4">
          <Card>
            <CardHeader><CardTitle className="text-base">About this Course</CardTitle></CardHeader>
            <CardContent className="space-y-3">
              <p className="text-sm text-muted-foreground">{course.description || "No description available."}</p>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div><span className="text-muted-foreground">Enrolled Students:</span> <span className="font-medium">{course.enrolled}</span></div>
                <div><span className="text-muted-foreground">Max Capacity:</span> <span className="font-medium">{course.max_capacity}</span></div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
