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 { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, CheckCircle2, XCircle, Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { admissionService } from "@/services/admission.service";
import { useCourses } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { AdmissionRegister, AdmissionRegisterCreateRequest } from "@/types/admission";

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

export default function AdmissionRegisterPage() {
  const { toast } = useToast();
  const qc = useQueryClient();
  const [showCreate, setShowCreate] = useState(false);

  const { data: registersData, isLoading } = useQuery({
    queryKey: ["admission-registers", "list"],
    queryFn: () => admissionService.listRegisters(),
  });
  const registers = registersData?.items ?? [];

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

  const [form, setForm] = useState<AdmissionRegisterCreateRequest>({
    name: "",
    course_id: 0,
    start_date: "",
    end_date: "",
    min_count: undefined,
    max_count: undefined,
  });

  const createMutation = useMutation({
    mutationFn: (data: AdmissionRegisterCreateRequest) => admissionService.createRegister(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["admission-registers"] });
      toast({ title: "Register created" });
      setShowCreate(false);
      setForm({ name: "", course_id: 0, start_date: "", end_date: "" });
    },
    onError: () => toast({ title: "Error", description: "Failed to create register", variant: "destructive" }),
  });

  const confirmMutation = useMutation({
    mutationFn: (id: number) => admissionService.confirmRegister(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admission-registers"] }); toast({ title: "Register confirmed" }); },
    onError: () => toast({ title: "Error", description: "Failed to confirm", variant: "destructive" }),
  });

  const closeMutation = useMutation({
    mutationFn: (id: number) => admissionService.closeRegister(id),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admission-registers"] }); toast({ title: "Register closed" }); },
    onError: () => toast({ title: "Error", description: "Failed to close", 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">Admission Registers</h1>
          <p className="text-muted-foreground">Manage admission registers and their status.</p>
        </div>
        <Dialog open={showCreate} onOpenChange={setShowCreate}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Create Register</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader><DialogTitle>Create Admission Register</DialogTitle></DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input placeholder="e.g. Fall 2025 Intake" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
              </div>
              <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 course" /></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="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>Min Count</Label>
                  <Input type="number" value={form.min_count ?? ""} onChange={e => setForm({ ...form, min_count: e.target.value ? Number(e.target.value) : undefined })} />
                </div>
                <div className="space-y-2">
                  <Label>Max Count</Label>
                  <Input type="number" value={form.max_count ?? ""} onChange={e => setForm({ ...form, max_count: e.target.value ? Number(e.target.value) : undefined })} />
                </div>
              </div>
              <Button className="w-full" onClick={() => createMutation.mutate(form)} disabled={createMutation.isPending || !form.name || !form.course_id}>
                {createMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create Register
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>
                <TableHead>Course</TableHead>
                <TableHead>Dates</TableHead>
                <TableHead>Capacity</TableHead>
                <TableHead>Applications</TableHead>
                <TableHead>State</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {registers.map((reg: AdmissionRegister) => (
                <TableRow key={reg.id}>
                  <TableCell className="font-medium">{reg.name}</TableCell>
                  <TableCell>{reg.course_name}</TableCell>
                  <TableCell className="text-sm text-muted-foreground">{reg.start_date} — {reg.end_date}</TableCell>
                  <TableCell>{reg.min_count}–{reg.max_count}</TableCell>
                  <TableCell><Badge variant="secondary">{reg.application_count}</Badge></TableCell>
                  <TableCell>
                    <Badge variant={stateBadgeVariant[reg.state] ?? "outline"} className="capitalize">{reg.state}</Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-1">
                      {reg.state === "draft" && (
                        <Button variant="ghost" size="sm" onClick={() => confirmMutation.mutate(reg.id)} disabled={confirmMutation.isPending}>
                          <CheckCircle2 className="mr-1 h-3 w-3" /> Confirm
                        </Button>
                      )}
                      {reg.state === "confirm" && (
                        <Button variant="ghost" size="sm" onClick={() => closeMutation.mutate(reg.id)} disabled={closeMutation.isPending}>
                          <XCircle className="mr-1 h-3 w-3" /> Close
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {registers.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">No admission registers found.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
