import { useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { BookOpen, ArrowRight } from "lucide-react";
import { useSubjects, useProficiencySummary } from "@/hooks/queries";

export default function SubjectSelection() {
  const navigate = useNavigate();
  const { data: subjects = [], isLoading: ls } = useSubjects();
  const { data: summaries = [], isLoading: lp } = useProficiencySummary();

  if (ls || lp) 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 getSummary = (subjectId: number) => summaries.find(s => s.subject_id === subjectId);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">My Subjects</h1>
        <p className="text-muted-foreground">Select a subject to view your progress or start a diagnostic assessment.</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {subjects.map((subject) => {
          const summary = getSummary(subject.id);
          const mastery = summary?.overall_mastery ?? 0;
          const hasTaken = !!summary;

          return (
            <Card key={subject.id} className="hover:shadow-md transition-shadow">
              <CardHeader>
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                    <BookOpen className="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <CardTitle className="text-lg">{subject.name}</CardTitle>
                    <CardDescription>{subject.code}</CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                {hasTaken ? (
                  <>
                    <div className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span className="text-muted-foreground">Overall Mastery</span>
                        <span className="font-medium">{Math.round(mastery)}%</span>
                      </div>
                      <Progress value={mastery} className="h-2" />
                    </div>
                    <div className="flex items-center justify-between text-sm text-muted-foreground">
                      <span>{summary?.topics_mastered ?? 0} / {summary?.topics_total ?? 0} topics mastered</span>
                    </div>
                    <div className="flex gap-2">
                      <Button variant="outline" size="sm" className="flex-1" onClick={() => navigate(`/student/proficiency/${subject.id}`)}>
                        View Profile
                      </Button>
                      <Button size="sm" className="flex-1" onClick={() => navigate(`/student/plan/${subject.id}`)}>
                        Learning Plan <ArrowRight className="ms-1 h-3 w-3 rtl:rotate-180" />
                      </Button>
                    </div>
                  </>
                ) : (
                  <>
                    <p className="text-sm text-muted-foreground">Take a diagnostic assessment to discover your proficiency level and get a personalized learning plan.</p>
                    <Button className="w-full" onClick={() => navigate(`/student/diagnostic/${subject.id}`)}>
                      Start Diagnostic <ArrowRight className="ms-1 h-4 w-4 rtl:rotate-180" />
                    </Button>
                  </>
                )}
              </CardContent>
            </Card>
          );
        })}
        {subjects.length === 0 && (
          <div className="col-span-full text-center py-12 text-muted-foreground">
            <BookOpen className="h-12 w-12 mx-auto mb-3 opacity-40" />
            <p>No subjects available yet.</p>
          </div>
        )}
      </div>
    </div>
  );
}
