import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useStudentProgressList, useStudentProgressDetail } from "@/hooks/queries";
import { Search, TrendingUp, Loader2 } from "lucide-react";
import type { StudentProgression } from "@/types/student-progress";

function rateColor(rate: number | null | undefined): string {
  if (rate == null) return "bg-muted text-muted-foreground";
  if (rate >= 85) return "bg-emerald-100 text-emerald-700 border-emerald-200";
  if (rate >= 60) return "bg-amber-100 text-amber-700 border-amber-200";
  return "bg-red-100 text-red-700 border-red-200";
}

export default function AdminStudentProgress() {
  const [search, setSearch] = useState("");
  const [drillId, setDrillId] = useState<number | null>(null);
  const { data, isLoading } = useStudentProgressList({ q: search || undefined, size: 200 });
  const items = (data?.data ?? data?.items ?? []) as StudentProgression[];

  const { data: detail, isLoading: loadingDetail } = useStudentProgressDetail(drillId);

  if (isLoading) {
    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>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <TrendingUp className="h-7 w-7" />
          Student progress
        </h1>
        <p className="text-muted-foreground">
          Per-student attendance, assignments and marksheet activity across the institution. Click a row for the breakdown.
        </p>
      </div>
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search students or GR number..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-12">#</TableHead>
                <TableHead>Student</TableHead>
                <TableHead>GR No.</TableHead>
                <TableHead className="text-right">Attendance</TableHead>
                <TableHead className="text-right">Assignments</TableHead>
                <TableHead className="text-right">Marksheet lines</TableHead>
                <TableHead className="text-right">Avg marks</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {items.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground py-10">
                    No students match your search.
                  </TableCell>
                </TableRow>
              )}
              {items.map((r, i) => (
                <TableRow
                  key={r.id}
                  className="cursor-pointer hover:bg-accent/50"
                  onClick={() => setDrillId(r.id)}
                >
                  <TableCell>{i + 1}</TableCell>
                  <TableCell className="font-medium">{r.student_name || "—"}</TableCell>
                  <TableCell className="text-muted-foreground text-xs">{r.gr_no || "—"}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <span className="tabular-nums">
                        {r.total_attendance_present ?? 0}/{r.total_attendance ?? 0}
                      </span>
                      {r.attendance_rate != null && (
                        <Badge variant="outline" className={rateColor(r.attendance_rate)}>
                          {r.attendance_rate}%
                        </Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-right tabular-nums">{r.total_assignment ?? 0}</TableCell>
                  <TableCell className="text-right tabular-nums">{r.total_marksheet_line ?? 0}</TableCell>
                  <TableCell className="text-right tabular-nums">
                    {r.avg_marks != null ? r.avg_marks : "—"}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={!!drillId} onOpenChange={(open) => !open && setDrillId(null)}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>
              {detail?.student_name || "Student breakdown"}
              {detail?.gr_no ? (
                <span className="text-sm text-muted-foreground ml-2">GR {detail.gr_no}</span>
              ) : null}
            </DialogTitle>
          </DialogHeader>
          {loadingDetail && (
            <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
          )}
          {detail && !loadingDetail && (
            <div className="space-y-6 max-h-[70vh] overflow-y-auto">
              <section>
                <h3 className="text-sm font-medium mb-2">Recent attendance ({detail.attendance.length})</h3>
                <div className="rounded border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Sheet</TableHead>
                        <TableHead className="text-right">Present</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {detail.attendance.length === 0 && (
                        <TableRow><TableCell colSpan={2} className="text-center text-muted-foreground py-4">No attendance records.</TableCell></TableRow>
                      )}
                      {detail.attendance.map((a) => (
                        <TableRow key={a.id}>
                          <TableCell className="text-sm">{a.sheet || "—"}</TableCell>
                          <TableCell className="text-right">
                            {a.present == null ? "—" : a.present ? (
                              <Badge variant="outline" className="bg-emerald-50 text-emerald-700 border-emerald-200">Present</Badge>
                            ) : (
                              <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">Absent</Badge>
                            )}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </section>

              <section>
                <h3 className="text-sm font-medium mb-2">Recent assignments ({detail.assignments.length})</h3>
                <div className="rounded border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Assignment</TableHead>
                        <TableHead className="text-right">Marks</TableHead>
                        <TableHead className="text-right">State</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {detail.assignments.length === 0 && (
                        <TableRow><TableCell colSpan={3} className="text-center text-muted-foreground py-4">No assignment submissions.</TableCell></TableRow>
                      )}
                      {detail.assignments.map((a) => (
                        <TableRow key={a.id}>
                          <TableCell className="text-sm">{a.assignment || "—"}</TableCell>
                          <TableCell className="text-right tabular-nums">{a.marks ?? 0}</TableCell>
                          <TableCell className="text-right"><Badge variant="outline" className="capitalize">{a.state || "—"}</Badge></TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </section>

              <section>
                <h3 className="text-sm font-medium mb-2">Marksheet lines ({detail.marksheets.length})</h3>
                <div className="rounded border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Marksheet</TableHead>
                        <TableHead className="text-right">Marks</TableHead>
                        <TableHead className="text-right">Grade</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {detail.marksheets.length === 0 && (
                        <TableRow><TableCell colSpan={3} className="text-center text-muted-foreground py-4">No marksheet lines.</TableCell></TableRow>
                      )}
                      {detail.marksheets.map((m) => (
                        <TableRow key={m.id}>
                          <TableCell className="text-sm">{m.marksheet || "—"}</TableCell>
                          <TableCell className="text-right tabular-nums">{m.marks ?? 0}</TableCell>
                          <TableCell className="text-right">{m.grade || "—"}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </section>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
