import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
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, DialogTrigger } from "@/components/ui/dialog";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, ChevronRight, CalendarCheck, CheckCircle2, Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { institutionalExamService } from "@/services/institutional-exam.service";
import { useCourses, useBatches } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { InstitutionalExamSession, InstitutionalExam } from "@/types/institutional-exam";

const stateBadgeVariant: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
  draft: "outline",
  schedule: "secondary",
  held: "default",
  cancel: "destructive",
  done: "default",
};

export default function InstitutionalExamSessions() {
  const { toast } = useToast();
  const qc = useQueryClient();
  const [showCreate, setShowCreate] = useState(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);

  const { data: sessionsData, isLoading } = useQuery({
    queryKey: ["inst-exam-sessions", "list"],
    queryFn: () => institutionalExamService.listSessions(),
  });
  const sessions = sessionsData?.items ?? [];

  const { data: expandedSession } = useQuery({
    queryKey: ["inst-exam-sessions", expandedId],
    queryFn: () => institutionalExamService.getSession(expandedId!),
    enabled: !!expandedId,
  });

  const { data: examTypesData } = useQuery({
    queryKey: ["exam-types", "list"],
    queryFn: () => institutionalExamService.listExamTypes(),
  });
  const examTypes = examTypesData?.items ?? [];

  const { data: coursesData } = useCourses();
  const courses = coursesData?.items ?? [];
  const { data: batchesData } = useBatches();
  const batches = batchesData?.items ?? [];

  const [form, setForm] = useState({
    name: "",
    course_id: 0,
    batch_id: 0,
    start_date: "",
    end_date: "",
    exam_type_id: 0,
    evaluation_type: "normal" as "normal" | "grade",
  });

  const createMutation = useMutation({
    mutationFn: () => institutionalExamService.createSession(form as Parameters<typeof institutionalExamService.createSession>[0]),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["inst-exam-sessions"] });
      toast({ title: "Exam session created" });
      setShowCreate(false);
      setForm({ name: "", course_id: 0, batch_id: 0, start_date: "", end_date: "", exam_type_id: 0, evaluation_type: "normal" });
    },
    onError: () => toast({ title: "Error", description: "Failed to create session", variant: "destructive" }),
  });

  const scheduleMutation = useMutation({
    mutationFn: (id: number) => institutionalExamService.scheduleSession(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["inst-exam-sessions"] }); toast({ title: "Session scheduled" }); },
    onError: () => toast({ title: "Error", description: "Failed to schedule", variant: "destructive" }),
  });

  const doneMutation = useMutation({
    mutationFn: (id: number) => institutionalExamService.markSessionDone(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["inst-exam-sessions"] }); toast({ title: "Session marked as done" }); },
    onError: () => toast({ title: "Error", description: "Failed to update", variant: "destructive" }),
  });

  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 className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Exam Sessions</h1>
          <p className="text-muted-foreground">Manage institutional exam sessions and their exams.</p>
        </div>
        <Dialog open={showCreate} onOpenChange={setShowCreate}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Create Session</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Create Exam Session</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input placeholder="e.g. Mid-Term Exams 2025" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Course</Label>
                  <Select value={form.course_id ? form.course_id.toString() : ""} onValueChange={v => setForm({ ...form, course_id: Number(v) })}>
                    <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>
                      {courses.map((c) => (
                        <SelectItem key={c.id} value={c.id.toString()}>{(c as { title?: string; name?: string }).title || (c as { name?: string }).name || `Course #${c.id}`}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Batch</Label>
                  <Select value={form.batch_id ? form.batch_id.toString() : ""} onValueChange={v => setForm({ ...form, batch_id: Number(v) })}>
                    <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>
                      {batches.map((b: { id: number; name: string }) => (
                        <SelectItem key={b.id} value={b.id.toString()}>{b.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Start Date</Label>
                  <Input type="date" value={form.start_date} onChange={e => setForm({ ...form, start_date: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>End Date</Label>
                  <Input type="date" value={form.end_date} onChange={e => setForm({ ...form, end_date: e.target.value })} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Exam Type</Label>
                  <Select value={form.exam_type_id ? form.exam_type_id.toString() : ""} onValueChange={v => setForm({ ...form, exam_type_id: Number(v) })}>
                    <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                    <SelectContent>
                      {examTypes.map((t: { id: number; name: string }) => (
                        <SelectItem key={t.id} value={t.id.toString()}>{t.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Evaluation Type</Label>
                  <Select value={form.evaluation_type} onValueChange={v => setForm({ ...form, evaluation_type: v as "normal" | "grade" })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="normal">Normal</SelectItem>
                      <SelectItem value="grade">Grade</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <Button className="w-full" onClick={() => createMutation.mutate()} disabled={createMutation.isPending || !form.name || !form.course_id || !form.batch_id}>
                {createMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Session
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead />
                <TableHead>Name</TableHead>
                <TableHead>Course / Batch</TableHead>
                <TableHead>Dates</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Exams</TableHead>
                <TableHead>State</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sessions.map((session: InstitutionalExamSession) => (
                <Collapsible key={session.id} asChild open={expandedId === session.id} onOpenChange={open => setExpandedId(open ? session.id : null)}>
                  <>
                    <TableRow>
                      <TableCell>
                        <CollapsibleTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-6 w-6">
                            <ChevronRight className={`h-4 w-4 transition-transform ${expandedId === session.id ? "rotate-90" : ""}`} />
                          </Button>
                        </CollapsibleTrigger>
                      </TableCell>
                      <TableCell className="font-medium">{session.name}</TableCell>
                      <TableCell>
                        <div>
                          <span className="text-sm">{session.course_name}</span>
                          <span className="text-xs text-muted-foreground ml-1">/ {session.batch_name}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">{session.start_date} — {session.end_date}</TableCell>
                      <TableCell><Badge variant="outline">{session.exam_type_name}</Badge></TableCell>
                      <TableCell><Badge variant="secondary">{session.exam_count}</Badge></TableCell>
                      <TableCell>
                        <Badge variant={stateBadgeVariant[session.state] ?? "outline"} className="capitalize">{session.state}</Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          {session.state === "draft" && (
                            <Button variant="ghost" size="sm" onClick={() => scheduleMutation.mutate(session.id)} disabled={scheduleMutation.isPending}>
                              <CalendarCheck className="mr-1 h-3 w-3" /> Schedule
                            </Button>
                          )}
                          {session.state === "schedule" && (
                            <Button variant="ghost" size="sm" onClick={() => doneMutation.mutate(session.id)} disabled={doneMutation.isPending}>
                              <CheckCircle2 className="mr-1 h-3 w-3" /> Done
                            </Button>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                    <CollapsibleContent asChild>
                      <TableRow>
                        <TableCell colSpan={8} className="bg-muted/50 p-4">
                          {expandedSession && expandedId === session.id ? (
                            <div className="space-y-2">
                              <h4 className="text-sm font-medium">Exams in Session</h4>
                              {(expandedSession as InstitutionalExamSession & { exams?: InstitutionalExam[] }).exams?.length ? (
                                <div className="grid gap-2">
                                  {((expandedSession as InstitutionalExamSession & { exams?: InstitutionalExam[] }).exams ?? []).map((exam: InstitutionalExam) => (
                                    <div key={exam.id} className="flex items-center justify-between rounded border p-3 bg-background">
                                      <div>
                                        <span className="text-sm font-medium">{exam.name}</span>
                                        <span className="text-xs text-muted-foreground ml-2">{exam.subject_name}</span>
                                      </div>
                                      <div className="flex items-center gap-2">
                                        <span className="text-xs text-muted-foreground">{exam.total_marks} marks</span>
                                        <Badge variant="outline" className="text-xs capitalize">{exam.state}</Badge>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              ) : (
                                <p className="text-sm text-muted-foreground">No exams in this session yet.</p>
                              )}
                            </div>
                          ) : (
                            <div className="flex justify-center py-4"><Loader2 className="h-4 w-4 animate-spin text-muted-foreground" /></div>
                          )}
                        </TableCell>
                      </TableRow>
                    </CollapsibleContent>
                  </>
                </Collapsible>
              ))}
              {sessions.length === 0 && (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">No exam sessions found.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
