import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { BookOpen, ClipboardList, BarChart3, Calendar, ArrowRight } from "lucide-react";
import { Link } from "react-router-dom";
import { useCourses, useAssignments, useGrades } from "@/hooks/queries";
import AiStudyCoach from "@/components/ai/AiStudyCoach";
import AiTipBanner from "@/components/ai/AiTipBanner";

export default function StudentDashboard() {
  const { data: coursesData, isLoading: lc } = useCourses();
  const { data: assignmentsData, isLoading: la } = useAssignments();
  const { data: gradesData, isLoading: lg } = useGrades();
  const courses = coursesData?.items ?? [];
  const assignments = assignmentsData?.items ?? [];
  const gradeRecords = gradesData ?? [];
  if (lc || la || 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 myCourses = courses.filter(c => ["c1", "c2", "c5", "c8"].includes(c.id));
  const upcomingAssignments = assignments.filter(a => a.status === "pending").slice(0, 3);
  const recentGrades = gradeRecords.slice(0, 3);
  const stats = [
    { label: "Enrolled Courses", value: String(myCourses.length), icon: BookOpen, color: "text-primary" },
    { label: "Pending Assignments", value: String(assignments.filter(a => a.status === "pending").length), icon: ClipboardList, color: "text-warning" },
    { label: "Average Grade", value: "78%", icon: BarChart3, color: "text-success" },
    { label: "Attendance Rate", value: "94%", icon: Calendar, color: "text-info" },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Welcome back, Sarah!</h1>
        <p className="text-muted-foreground">Here's an overview of your learning progress.</p>
      </div>

      <AiTipBanner context="student-dashboard" variant="tip" />

      <AiStudyCoach />

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((s) => (
          <Card key={s.label}>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">{s.label}</p>
                  <p className="text-2xl font-bold">{s.value}</p>
                </div>
                <s.icon className={`h-8 w-8 ${s.color} opacity-80`} />
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-lg">My Courses</CardTitle>
            <Button variant="ghost" size="sm" asChild><Link to="/student/courses">View All <ArrowRight className="ml-1 h-3 w-3" /></Link></Button>
          </CardHeader>
          <CardContent className="space-y-4">
            {myCourses.map((c) => (
              <Link to={`/student/courses/${c.id}`} key={c.id} className="block">
                <div className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors">
                  <div className="min-w-0">
                    <p className="font-medium text-sm truncate">{c.title}</p>
                    <p className="text-xs text-muted-foreground">{c.instructor}</p>
                  </div>
                  <div className="flex items-center gap-3 shrink-0">
                    <div className="w-24"><Progress value={c.progress} className="h-2" /></div>
                    <span className="text-xs font-medium w-8 text-right">{c.progress}%</span>
                  </div>
                </div>
              </Link>
            ))}
          </CardContent>
        </Card>

        <div className="space-y-6">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-lg">Upcoming Assignments</CardTitle>
              <Button variant="ghost" size="sm" asChild><Link to="/student/assignments">View All <ArrowRight className="ml-1 h-3 w-3" /></Link></Button>
            </CardHeader>
            <CardContent className="space-y-3">
              {upcomingAssignments.map((a) => (
                <div key={a.id} className="flex items-center justify-between p-2 rounded border">
                  <div><p className="text-sm font-medium">{a.title}</p><p className="text-xs text-muted-foreground">{a.courseName}</p></div>
                  <Badge variant="outline" className="text-xs">{a.dueDate}</Badge>
                </div>
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-lg">Recent Grades</CardTitle>
              <Button variant="ghost" size="sm" asChild><Link to="/student/grades">View All <ArrowRight className="ml-1 h-3 w-3" /></Link></Button>
            </CardHeader>
            <CardContent className="space-y-3">
              {recentGrades.map((g) => (
                <div key={g.id} className="flex items-center justify-between p-2 rounded border">
                  <div><p className="text-sm font-medium">{g.assignmentTitle}</p><p className="text-xs text-muted-foreground">{g.courseName}</p></div>
                  <span className="text-sm font-bold text-primary">{g.grade}/{g.maxGrade}</span>
                </div>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
