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 { useCourses, useAssignments, useAttendance, useGrades } from "@/hooks/queries";
import { ArrowLeft, CheckCircle, Circle, FileText, Video, HelpCircle } from "lucide-react";

const iconMap = { video: Video, reading: FileText, quiz: HelpCircle };

export default function StudentCourseDetail() {
  const { id } = useParams();
  const { data: coursesData, isLoading: lc } = useCourses();
  const { data: assignmentsData, isLoading: la } = useAssignments();
  const { data: attendanceData, isLoading: lat } = useAttendance();
  const { data: gradesData, isLoading: lg } = useGrades();
  const courses = coursesData?.items ?? [];
  const assignments = assignmentsData?.items ?? [];
  const attendanceRecords = attendanceData ?? [];
  const gradeRecords = gradesData ?? [];
  if (lc || la || lat || 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>;

  const course = courses.find(c => c.id === id);

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

  const courseAssignments = assignments.filter(a => a.courseId === id);
  const courseAttendance = attendanceRecords.filter(a => a.courseId === id);
  const courseGrades = gradeRecords.filter(g => g.courseId === id);

  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" /></Link></Button>
        <div>
          <h1 className="text-2xl font-bold">{course.title}</h1>
          <p className="text-muted-foreground">{course.instructor} · {course.code}</p>
        </div>
      </div>

      <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">{course.progress}%</span>
          </div>
          <Progress value={course.progress} className="h-3" />
        </CardContent>
      </Card>

      <Tabs defaultValue="materials">
        <TabsList>
          <TabsTrigger value="materials">Materials</TabsTrigger>
          <TabsTrigger value="assignments">Assignments ({courseAssignments.length})</TabsTrigger>
          <TabsTrigger value="attendance">Attendance</TabsTrigger>
          <TabsTrigger value="grades">Grades</TabsTrigger>
        </TabsList>

        <TabsContent value="materials" className="space-y-4 mt-4">
          {course.modules.length === 0 ? (
            <p className="text-muted-foreground text-sm py-8 text-center">No modules available yet.</p>
          ) : course.modules.map(mod => (
            <Card key={mod.id}>
              <CardHeader className="pb-2">
                <CardTitle className="text-base">{mod.title}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {mod.lessons.map(lesson => {
                  const Icon = iconMap[lesson.type];
                  return (
                    <div key={lesson.id} className="flex items-center gap-3 p-2 rounded hover:bg-muted/50">
                      {lesson.completed ? <CheckCircle className="h-4 w-4 text-success shrink-0" /> : <Circle className="h-4 w-4 text-muted-foreground shrink-0" />}
                      <Icon className="h-4 w-4 text-muted-foreground shrink-0" />
                      <span className="text-sm flex-1">{lesson.title}</span>
                      <span className="text-xs text-muted-foreground">{lesson.duration}</span>
                    </div>
                  );
                })}
              </CardContent>
            </Card>
          ))}
        </TabsContent>

        <TabsContent value="assignments" className="mt-4 space-y-3">
          {courseAssignments.map(a => (
            <Card key={a.id}>
              <CardContent className="pt-4 flex items-center justify-between">
                <div>
                  <p className="font-medium text-sm">{a.title}</p>
                  <p className="text-xs text-muted-foreground">Due: {a.dueDate}</p>
                </div>
                <Badge variant={a.status === "graded" ? "default" : a.status === "overdue" ? "destructive" : "secondary"}>
                  {a.status}
                </Badge>
              </CardContent>
            </Card>
          ))}
        </TabsContent>

        <TabsContent value="attendance" className="mt-4 space-y-3">
          {courseAttendance.map(a => (
            <div key={a.id} className="flex items-center justify-between p-3 rounded border">
              <span className="text-sm">{a.date}</span>
              <Badge variant={a.status === "present" ? "default" : a.status === "absent" ? "destructive" : "secondary"}>
                {a.status}
              </Badge>
            </div>
          ))}
        </TabsContent>

        <TabsContent value="grades" className="mt-4 space-y-3">
          {courseGrades.map(g => (
            <div key={g.id} className="flex items-center justify-between p-3 rounded border">
              <div>
                <p className="text-sm font-medium">{g.assignmentTitle}</p>
                <p className="text-xs text-muted-foreground">{g.date}</p>
              </div>
              <span className="font-bold text-primary">{g.grade}/{g.maxGrade}</span>
            </div>
          ))}
        </TabsContent>
      </Tabs>
    </div>
  );
}
