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, Play } from "lucide-react";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useMyEnrolledCourses, useGrades } from "@/hooks/queries";
import { useAuth } from "@/contexts/AuthContext";
import AiStudyCoach from "@/components/ai/AiStudyCoach";
import AiTipBanner from "@/components/ai/AiTipBanner";

export default function StudentDashboard() {
  const { user } = useAuth();
  const { t } = useTranslation();
  const { data: enrolledData, isLoading: lc } = useMyEnrolledCourses();
  const { data: gradesData, isLoading: lg } = useGrades();
  const myCourses = enrolledData?.items ?? [];
  const gradeRecords = gradesData ?? [];
  if (lc || 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 recentGrades = gradeRecords.slice(0, 3);
  const avgProgress = myCourses.length > 0 ? Math.round(myCourses.reduce((s, c) => s + c.progress, 0) / myCourses.length) : 0;
  const avgGrade = gradeRecords.length > 0
    ? Math.round(gradeRecords.reduce((s, g) => s + (g.grade / g.max_grade) * 100, 0) / gradeRecords.length)
    : 0;
  const firstName = user?.name?.split(" ")[0] || t("dashboard.greetingFallback");

  const stats = [
    { label: t("studentDash.enrolledCourses"), value: String(myCourses.length), icon: BookOpen, color: "text-primary" },
    { label: t("studentDash.overallProgress"), value: `${avgProgress}%`, icon: ClipboardList, color: "text-warning" },
    { label: t("studentDash.averageGrade"), value: gradeRecords.length > 0 ? `${avgGrade}%` : "N/A", icon: BarChart3, color: "text-success" },
    { label: t("studentDash.totalChapters"), value: String(myCourses.reduce((s, c) => s + c.chapter_count, 0)), icon: Calendar, color: "text-info" },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">{t("studentDash.welcome", { name: firstName })}</h1>
        <p className="text-muted-foreground">{t("studentDash.subtitle")}</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 gap-3">
                <div className="min-w-0">
                  <p className="text-sm text-muted-foreground">{s.label}</p>
                  <p className="text-2xl font-bold"><bdi>{s.value}</bdi></p>
                </div>
                <s.icon className={`h-8 w-8 ${s.color} opacity-80 shrink-0`} />
              </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">{t("studentDash.myCourses")}</CardTitle>
            <Button variant="ghost" size="sm" asChild>
              <Link to="/student/courses">
                {t("common.viewAll")} <ArrowRight className="ms-1 h-3 w-3 rtl:rotate-180" />
              </Link>
            </Button>
          </CardHeader>
          <CardContent className="space-y-4">
            {myCourses.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">{t("studentDash.noEnrolledCourses")}</p>
            ) : 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 || c.name}</p>
                    <p className="text-xs text-muted-foreground">
                      {t("studentDash.chaptersMaterials", { chapters: c.chapter_count, materials: c.total_materials })}
                    </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-end"><bdi>{c.progress}%</bdi></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">{t("studentDash.quickActions")}</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {myCourses.slice(0, 3).map(c => (
                <Link key={c.id} to={`/student/courses/${c.id}`} className="flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors">
                  <Play className="h-4 w-4 text-primary shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium truncate">
                      {c.progress > 0 ? t("studentDash.continue") : t("studentDash.start")} {c.title || c.name}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {t("studentDash.chaptersDone", { done: c.completed_chapters, total: c.chapter_count })}
                    </p>
                  </div>
                  <Badge variant="outline"><bdi>{c.progress}%</bdi></Badge>
                </Link>
              ))}
              {myCourses.length === 0 && (
                <p className="text-sm text-muted-foreground text-center py-4">{t("studentDash.enrollToStart")}</p>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-lg">{t("studentDash.recentGrades")}</CardTitle>
              <Button variant="ghost" size="sm" asChild>
                <Link to="/student/grades">
                  {t("common.viewAll")} <ArrowRight className="ms-1 h-3 w-3 rtl:rotate-180" />
                </Link>
              </Button>
            </CardHeader>
            <CardContent className="space-y-3">
              {recentGrades.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">{t("studentDash.noGradesYet")}</p>
              ) : recentGrades.map((g) => (
                <div key={g.id} className="flex items-center justify-between p-2 rounded border gap-3">
                  <div className="min-w-0"><p className="text-sm font-medium truncate" dir="auto">{g.assignment_title}</p><p className="text-xs text-muted-foreground truncate" dir="auto">{g.course_name}</p></div>
                  <span className="text-sm font-bold text-primary shrink-0"><bdi>{g.grade}/{g.max_grade}</bdi></span>
                </div>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
