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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { useBatches, useStudents } from "@/hooks/queries";
import { lmsService } from "@/services/lms.service";
import { useMutation } from "@tanstack/react-query";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts";
import { useToast } from "@/hooks/use-toast";
import AiAlertBanner from "@/components/ai/AiAlertBanner";
import AiRiskBadge from "@/components/ai/AiRiskBadge";

const trendData = [
  { week: "W1", rate: 92 }, { week: "W2", rate: 88 }, { week: "W3", rate: 95 },
  { week: "W4", rate: 85 }, { week: "W5", rate: 90 }, { week: "W6", rate: 87 },
];

export default function TeacherAttendance() {
  const { data: batchesData, isLoading: lb } = useBatches();
  const { data: studentsData, isLoading: ls } = useStudents({ size: 500 });
  const batches = batchesData?.items ?? [];
  const students = studentsData?.items ?? [];
  const [batchIdStr, setBatchIdStr] = useState("");
  const [markOpen, setMarkOpen] = useState(false);
  const [attendanceMap, setAttendanceMap] = useState<Record<number, string>>({});
  const { toast } = useToast();

  const saveMut = useMutation({
    mutationFn: (data: { course_id: number; date: string; records: { student_id: number; status: string }[] }) =>
      lmsService.recordAttendance(data),
    onSuccess: () => { setMarkOpen(false); toast({ title: "Attendance saved" }); },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  if (lb || ls) 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 effectiveBatchId = batchIdStr ? Number(batchIdStr) : batches[0]?.id;
  const batch = batches.find(b => b.id === effectiveBatchId);
  const batchStudents = students.filter((s) => s.batch_id === effectiveBatchId);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div><h1 className="text-2xl font-bold">Attendance</h1><p className="text-muted-foreground">Track and mark student attendance.</p></div>
        <Button onClick={() => setMarkOpen(true)}>Mark Attendance</Button>
      </div>

      <AiAlertBanner />

      <div className="flex items-center gap-3">
        <span className="text-sm text-muted-foreground">Batch:</span>
        <Select value={effectiveBatchId != null ? String(effectiveBatchId) : ""} onValueChange={setBatchIdStr}>
          <SelectTrigger className="w-64"><SelectValue /></SelectTrigger>
          <SelectContent>{batches.map(b => <SelectItem key={b.id} value={String(b.id)}>{b.name}</SelectItem>)}</SelectContent>
        </Select>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader><CardTitle className="text-lg">Attendance Trend</CardTitle></CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={220}>
              <LineChart data={trendData}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                <XAxis dataKey="week" className="fill-muted-foreground" tick={{ fontSize: 12 }} />
                <YAxis domain={[70, 100]} className="fill-muted-foreground" tick={{ fontSize: 12 }} />
                <Tooltip />
                <Line type="monotone" dataKey="rate" stroke="hsl(192, 82%, 32%)" strokeWidth={2} dot={{ r: 4 }} />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader><CardTitle className="text-lg">Students — {batch?.name}</CardTitle></CardHeader>
          <CardContent>
            <Table>
              <TableHeader><TableRow><TableHead>Student</TableHead><TableHead>Rate</TableHead><TableHead>AI Risk</TableHead></TableRow></TableHeader>
              <TableBody>
                {batchStudents.map(s => (
                  <TableRow key={s.id}>
                    <TableCell className="font-medium">{s.name}</TableCell>
                    <TableCell>—</TableCell>
                    <TableCell><AiRiskBadge /></TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>

      <Dialog open={markOpen} onOpenChange={setMarkOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Mark Attendance — {batch?.name}</DialogTitle></DialogHeader>
          <div className="space-y-3">
            {batchStudents.map(s => (
              <div key={s.id} className="flex items-center justify-between p-2 rounded border">
                <span className="text-sm font-medium">{s.name}</span>
                <Select value={attendanceMap[s.id] || "present"} onValueChange={(v) => setAttendanceMap(m => ({ ...m, [s.id]: v }))}>
                  <SelectTrigger className="w-28"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="present">Present</SelectItem><SelectItem value="absent">Absent</SelectItem>
                    <SelectItem value="late">Late</SelectItem><SelectItem value="excused">Excused</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            ))}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setMarkOpen(false)}>Cancel</Button>
            <Button disabled={saveMut.isPending} onClick={() => {
              const records = batchStudents.map(s => ({ student_id: s.id, status: attendanceMap[s.id] || "present" }));
              saveMut.mutate({ course_id: batch?.course_id || 0, date: new Date().toISOString().split("T")[0], records });
            }}>
              {saveMut.isPending ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
