import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { CheckCircle2, Loader2 } from "lucide-react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { admissionService } from "@/services/admission.service";
import { useToast } from "@/hooks/use-toast";
import type { AdmissionCreateRequest } from "@/types/admission";

type Step = "register" | "personal" | "review" | "success";

export default function AdmissionApplication() {
  const { toast } = useToast();
  const [step, setStep] = useState<Step>("register");
  const [selectedRegisterId, setSelectedRegisterId] = useState<number>(0);
  const [form, setForm] = useState<Omit<AdmissionCreateRequest, "register_id">>({
    first_name: "",
    last_name: "",
    email: "",
    gender: "m",
  });
  const [applicationNumber, setApplicationNumber] = useState("");

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

  const submitMutation = useMutation({
    mutationFn: async () => {
      const admission = await admissionService.createAdmission({ ...form, register_id: selectedRegisterId });
      await admissionService.submitAdmission(admission.id);
      return admission;
    },
    onSuccess: (data) => {
      setApplicationNumber(data.application_number);
      setStep("success");
    },
    onError: () => toast({ title: "Error", description: "Submission failed. Please try again.", variant: "destructive" }),
  });

  const canProceedFromRegister = selectedRegisterId > 0;
  const canProceedFromPersonal = form.first_name && form.last_name && form.email;

  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-4">
      <div className="w-full max-w-lg">
        {step !== "success" && (
          <div className="flex items-center justify-center gap-2 mb-8">
            {["register", "personal", "review"].map((s, i) => (
              <div key={s} className="flex items-center gap-2">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                  s === step ? "bg-primary text-primary-foreground" :
                  ["register", "personal", "review"].indexOf(step) > i ? "bg-primary/20 text-primary" : "bg-muted text-muted-foreground"
                }`}>
                  {i + 1}
                </div>
                {i < 2 && <div className="w-12 h-px bg-border" />}
              </div>
            ))}
          </div>
        )}

        {step === "register" && (
          <Card>
            <CardHeader>
              <CardTitle>Select Course</CardTitle>
              <CardDescription>Choose the admission register you want to apply to.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {loadingRegisters ? (
                <div className="flex justify-center py-8"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
              ) : (
                <div className="space-y-2">
                  {registers
                    .filter((r: { state: string }) => r.state === "confirm")
                    .map((r: { id: number; name: string; course_name: string; start_date: string; end_date: string }) => (
                      <button
                        key={r.id}
                        onClick={() => setSelectedRegisterId(r.id)}
                        className={`w-full text-left p-4 rounded-lg border transition-colors ${selectedRegisterId === r.id ? "bg-primary/10 border-primary" : "hover:bg-accent"}`}
                      >
                        <p className="font-medium">{r.name}</p>
                        <p className="text-sm text-muted-foreground">{r.course_name} · {r.start_date} — {r.end_date}</p>
                      </button>
                    ))}
                  {registers.filter((r: { state: string }) => r.state === "confirm").length === 0 && (
                    <p className="text-sm text-muted-foreground text-center py-4">No open admissions available.</p>
                  )}
                </div>
              )}
              <Button className="w-full" onClick={() => setStep("personal")} disabled={!canProceedFromRegister}>
                Next
              </Button>
            </CardContent>
          </Card>
        )}

        {step === "personal" && (
          <Card>
            <CardHeader>
              <CardTitle>Personal Information</CardTitle>
              <CardDescription>Fill in your personal details.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>First Name *</Label>
                  <Input value={form.first_name} onChange={e => setForm({ ...form, first_name: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>Last Name *</Label>
                  <Input value={form.last_name} onChange={e => setForm({ ...form, last_name: e.target.value })} />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Middle Name</Label>
                <Input value={form.middle_name ?? ""} onChange={e => setForm({ ...form, middle_name: e.target.value || undefined })} />
              </div>
              <div className="space-y-2">
                <Label>Email *</Label>
                <Input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Phone</Label>
                <Input value={form.phone ?? ""} onChange={e => setForm({ ...form, phone: e.target.value || undefined })} />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Birth Date</Label>
                  <Input type="date" value={form.birth_date ?? ""} onChange={e => setForm({ ...form, birth_date: e.target.value || undefined })} />
                </div>
                <div className="space-y-2">
                  <Label>Gender *</Label>
                  <Select value={form.gender} onValueChange={v => setForm({ ...form, gender: v as "m" | "f" | "o" })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="m">Male</SelectItem>
                      <SelectItem value="f">Female</SelectItem>
                      <SelectItem value="o">Other</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <div className="flex gap-3">
                <Button variant="outline" className="flex-1" onClick={() => setStep("register")}>Back</Button>
                <Button className="flex-1" onClick={() => setStep("review")} disabled={!canProceedFromPersonal}>Next</Button>
              </div>
            </CardContent>
          </Card>
        )}

        {step === "review" && (
          <Card>
            <CardHeader>
              <CardTitle>Review & Submit</CardTitle>
              <CardDescription>Please review your application before submitting.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-lg border p-4 space-y-2">
                <p className="text-sm font-medium">Course</p>
                <p className="text-sm text-muted-foreground">{selectedRegister?.name} — {selectedRegister?.course_name}</p>
              </div>
              <div className="rounded-lg border p-4 space-y-2">
                <p className="text-sm font-medium">Applicant</p>
                <p className="text-sm text-muted-foreground">{form.first_name} {form.middle_name ?? ""} {form.last_name}</p>
                <p className="text-sm text-muted-foreground">{form.email} {form.phone ? `· ${form.phone}` : ""}</p>
                <p className="text-sm text-muted-foreground capitalize">{form.gender === "m" ? "Male" : form.gender === "f" ? "Female" : "Other"} {form.birth_date ? `· ${form.birth_date}` : ""}</p>
              </div>
              <div className="flex gap-3">
                <Button variant="outline" className="flex-1" onClick={() => setStep("personal")}>Back</Button>
                <Button className="flex-1" onClick={() => submitMutation.mutate()} disabled={submitMutation.isPending}>
                  {submitMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Submit Application
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {step === "success" && (
          <Card>
            <CardContent className="pt-8 pb-8 text-center space-y-4">
              <CheckCircle2 className="h-16 w-16 text-green-500 mx-auto" />
              <div>
                <h2 className="text-xl font-bold">Application Submitted!</h2>
                <p className="text-muted-foreground mt-1">Your application has been received.</p>
              </div>
              <div className="rounded-lg bg-muted p-4">
                <p className="text-sm text-muted-foreground">Application Number</p>
                <p className="text-2xl font-bold">{applicationNumber}</p>
              </div>
              <p className="text-sm text-muted-foreground">Please save this number for future reference.</p>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
