import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader } 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 { Search } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { admissionService } from "@/services/admission.service";
import type { Admission, AdmissionState } from "@/types/admission";

const STATE_TABS: { value: string; label: string }[] = [
  { value: "all", label: "All" },
  { value: "draft", label: "Draft" },
  { value: "submit", label: "Submitted" },
  { value: "confirm", label: "Confirmed" },
  { value: "admission", label: "Admitted" },
  { value: "reject", label: "Rejected" },
];

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

export default function AdmissionList() {
  const navigate = useNavigate();
  const [search, setSearch] = useState("");
  const [stateFilter, setStateFilter] = useState("all");

  const { data, isLoading } = useQuery({
    queryKey: ["admissions", "list", { search, state: stateFilter === "all" ? undefined : stateFilter }],
    queryFn: () => admissionService.listAdmissions({
      search: search || undefined,
      state: stateFilter === "all" ? undefined : stateFilter,
    } as Parameters<typeof admissionService.listAdmissions>[0]),
  });
  const admissions = data?.items ?? [];

  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">Admissions</h1>
        <p className="text-muted-foreground">View and manage student admission applications.</p>
      </div>

      <div className="flex items-center gap-2">
        {STATE_TABS.map(tab => (
          <Button
            key={tab.value}
            variant={stateFilter === tab.value ? "default" : "outline"}
            size="sm"
            onClick={() => setStateFilter(tab.value)}
          >
            {tab.label}
          </Button>
        ))}
      </div>

      <Card>
        <CardHeader>
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input placeholder="Search by name..." value={search} onChange={e => setSearch(e.target.value)} className="pl-9" />
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Application #</TableHead>
                <TableHead>Name</TableHead>
                <TableHead>Course</TableHead>
                <TableHead>Register</TableHead>
                <TableHead>State</TableHead>
                <TableHead>Date</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {admissions.map((adm: Admission) => (
                <TableRow key={adm.id} className="cursor-pointer hover:bg-accent/50" onClick={() => navigate(`/admin/admissions/${adm.id}`)}>
                  <TableCell className="font-medium">{adm.application_number}</TableCell>
                  <TableCell>{adm.first_name} {adm.last_name}</TableCell>
                  <TableCell>{adm.course_name}</TableCell>
                  <TableCell className="text-muted-foreground">{adm.register_name}</TableCell>
                  <TableCell>
                    <Badge variant={stateBadgeVariant[adm.state] ?? "outline"} className="capitalize">{adm.state}</Badge>
                  </TableCell>
                  <TableCell className="text-muted-foreground">{new Date(adm.created_at).toLocaleDateString()}</TableCell>
                </TableRow>
              ))}
              {admissions.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">No admissions found.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
