import { useParams, useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ArrowLeft, Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { admissionService } from "@/services/admission.service";
import { useToast } from "@/hooks/use-toast";

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 AdmissionDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();
  const qc = useQueryClient();
  const admissionId = Number(id);

  const { data: admission, isLoading } = useQuery({
    queryKey: ["admissions", admissionId],
    queryFn: () => admissionService.getAdmission(admissionId),
    enabled: !!admissionId,
  });

  const makeTransition = (action: "submit" | "confirm" | "admit" | "reject") => {
    const fns = {
      submit: admissionService.submitAdmission,
      confirm: admissionService.confirmAdmission,
      admit: admissionService.admitAdmission,
      reject: admissionService.rejectAdmission,
    };
    return fns[action];
  };

  const transitionMutation = useMutation({
    mutationFn: ({ action }: { action: "submit" | "confirm" | "admit" | "reject" }) =>
      makeTransition(action)(admissionId),
    onSuccess: (_, { action }) => {
      qc.invalidateQueries({ queryKey: ["admissions"] });
      toast({ title: `Admission ${action}${action === "submit" ? "ted" : action === "reject" ? "ed" : "ed"}` });
    },
    onError: () => toast({ title: "Error", description: "Action failed", 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>;
  if (!admission) return <div className="text-center py-12 text-muted-foreground">Admission not found.</div>;

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={() => navigate("/admin/admissions")}>
          <ArrowLeft className="h-4 w-4 rtl:rotate-180" />
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold">{admission.first_name} {admission.last_name}</h1>
          <p className="text-muted-foreground">Application #{admission.application_number}</p>
        </div>
        <Badge variant={stateBadgeVariant[admission.state] ?? "outline"} className="capitalize text-sm px-3 py-1">
          {admission.state}
        </Badge>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader><CardTitle>Applicant Information</CardTitle></CardHeader>
          <CardContent>
            <dl className="space-y-3">
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Full Name</dt>
                <dd className="text-sm font-medium">{admission.first_name} {admission.middle_name ?? ""} {admission.last_name}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Email</dt>
                <dd className="text-sm font-medium">{admission.email}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Phone</dt>
                <dd className="text-sm font-medium">{admission.phone ?? "—"}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Birth Date</dt>
                <dd className="text-sm font-medium">{admission.birth_date ?? "—"}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Gender</dt>
                <dd className="text-sm font-medium capitalize">{admission.gender === "m" ? "Male" : admission.gender === "f" ? "Female" : "Other"}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Nationality</dt>
                <dd className="text-sm font-medium">{admission.nationality_name ?? "—"}</dd>
              </div>
            </dl>
          </CardContent>
        </Card>

        <Card>
          <CardHeader><CardTitle>Application Details</CardTitle></CardHeader>
          <CardContent>
            <dl className="space-y-3">
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Course</dt>
                <dd className="text-sm font-medium">{admission.course_name}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Register</dt>
                <dd className="text-sm font-medium">{admission.register_name}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Batch</dt>
                <dd className="text-sm font-medium">{admission.batch_name ?? "—"}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Fees</dt>
                <dd className="text-sm font-medium">{admission.fees}</dd>
              </div>
              <div className="flex justify-between">
                <dt className="text-sm text-muted-foreground">Applied On</dt>
                <dd className="text-sm font-medium">{new Date(admission.created_at).toLocaleDateString()}</dd>
              </div>
            </dl>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader><CardTitle>Actions</CardTitle></CardHeader>
        <CardContent>
          <div className="flex items-center gap-3">
            {admission.state === "draft" && (
              <Button onClick={() => transitionMutation.mutate({ action: "submit" })} disabled={transitionMutation.isPending}>
                {transitionMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Submit Application
              </Button>
            )}
            {admission.state === "submit" && (
              <>
                <Button onClick={() => transitionMutation.mutate({ action: "confirm" })} disabled={transitionMutation.isPending}>
                  {transitionMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Confirm
                </Button>
                <Button variant="destructive" onClick={() => transitionMutation.mutate({ action: "reject" })} disabled={transitionMutation.isPending}>
                  Reject
                </Button>
              </>
            )}
            {admission.state === "confirm" && (
              <>
                <Button onClick={() => transitionMutation.mutate({ action: "admit" })} disabled={transitionMutation.isPending}>
                  {transitionMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Admit
                </Button>
                <Button variant="destructive" onClick={() => transitionMutation.mutate({ action: "reject" })} disabled={transitionMutation.isPending}>
                  Reject
                </Button>
              </>
            )}
            {["admission", "reject", "done"].includes(admission.state) && (
              <p className="text-sm text-muted-foreground">No further actions available.</p>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
