import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useStudents } from "@/hooks/queries";
import { lmsStudentToUser } from "@/services/lms.service";
import type { User } from "@/types";
import { Search } from "lucide-react";
import AiRiskBadge from "@/components/ai/AiRiskBadge";
import AiGradeExplainer from "@/components/ai/AiGradeExplainer";

export default function TeacherStudents() {
  const { data: studentsData, isLoading } = useStudents({ size: 500 });
  const students = (studentsData?.items ?? []).map(lmsStudentToUser);
  const [search, setSearch] = useState("");
  const [selectedStudent, setSelectedStudent] = useState<User | null>(null);
  const filtered = students.filter(s => s.name.toLowerCase().includes(search.toLowerCase()) || s.email.toLowerCase().includes(search.toLowerCase()));

  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">My Students</h1><p className="text-muted-foreground">View and manage students across your courses.</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..." value={search} onChange={e => setSearch(e.target.value)} className="pl-9" />
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow><TableHead>Student</TableHead><TableHead>Batch</TableHead><TableHead>Attendance</TableHead><TableHead>Avg Grade</TableHead><TableHead>AI Risk</TableHead><TableHead>AI</TableHead><TableHead></TableHead></TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map(s => (
                <TableRow key={s.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <div className="h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center text-xs font-medium text-primary">{(s.avatar ?? s.name.slice(0, 1)).toUpperCase()}</div>
                      <div><p className="text-sm font-medium">{s.name}</p><p className="text-xs text-muted-foreground">{s.email}</p></div>
                    </div>
                  </TableCell>
                  <TableCell className="text-sm">{s.entities?.[0]?.name ?? "—"}</TableCell>
                  <TableCell className="text-sm">—</TableCell>
                  <TableCell className="text-sm">—</TableCell>
                  <TableCell><AiRiskBadge /></TableCell>
                  <TableCell><AiGradeExplainer studentName={s.name} /></TableCell>
                  <TableCell><Button size="sm" variant="ghost" onClick={() => setSelectedStudent(s)}>View</Button></TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={!!selectedStudent} onOpenChange={() => setSelectedStudent(null)}>
        <DialogContent>
          <DialogHeader><DialogTitle>{selectedStudent?.name}</DialogTitle></DialogHeader>
          {selectedStudent && (
            <div className="space-y-3">
              <p className="text-sm"><span className="text-muted-foreground">Email:</span> {selectedStudent.email}</p>
              <p className="text-sm"><span className="text-muted-foreground">Batch:</span> {selectedStudent.entities?.[0]?.name ?? "—"}</p>
              <p className="text-sm"><span className="text-muted-foreground">Attendance:</span> —</p>
              <p className="text-sm"><span className="text-muted-foreground">Average Grade:</span> —</p>
              <p className="text-sm"><span className="text-muted-foreground">Joined:</span> —</p>
              <p className="text-sm"><span className="text-muted-foreground">AI Risk:</span> <AiRiskBadge /></p>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
