"use client";

import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Separator } from "@/components/ui/separator";
import { Badge } from "@/components/ui/badge";
import {
    AlertCircle,
    Loader2,
    CreditCard,
    Info,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { paymentFormSchema, type PaymentFormSchema } from "../lib/schemas";
import {
    FEE_CONFIG,
    ACADEMIC_YEARS,
    SEMESTER_OPTIONS,
    PAYMENT_TYPE_OPTIONS,
} from "../lib/constants";
import { useInitiatePayment } from "../hooks/use-initiate-payment";
import { PaymentType } from "../lib/types";

export function PaymentForm() {
    const { mutate: initiatePayment, isPending, error } = useInitiatePayment();

    const form = useForm<PaymentFormSchema>({
        resolver: zodResolver(paymentFormSchema),
        defaultValues: {
            academic_session: "",
            academic_semester: undefined,
            payment_type: undefined,
            payment_mode: "FULL",
            amount: 0,
        },
    });

    const watchedPaymentType = form.watch("payment_type") as PaymentType | undefined;
    const watchedPaymentMode = form.watch("payment_mode");

    const selectedFee = watchedPaymentType ? FEE_CONFIG[watchedPaymentType] : null;
    const allowsInstallment = selectedFee?.allowsInstallment ?? false;

    // Sync amount and mode when payment type changes
    useEffect(() => {
        if (!watchedPaymentType) return;

        const fee = FEE_CONFIG[watchedPaymentType];

        // Reset mode to full if installment isn't allowed
        if (!fee.allowsInstallment) {
            form.setValue("payment_mode", "FULL");
        }

        // Auto-fill amount for full payment on fixed fees
        if (fee.amount > 0) {
            form.setValue("amount", fee.amount);
        } else {
            form.setValue("amount", 0);
        }

        form.clearErrors("amount");
        form.clearErrors("payment_mode");
    }, [watchedPaymentType, form]);

    // When switching to full mode, reset amount to the fee total
    useEffect(() => {
        if (watchedPaymentMode === "FULL" && watchedPaymentType) {
            const fee = FEE_CONFIG[watchedPaymentType];
            if (fee.amount > 0) {
                form.setValue("amount", fee.amount);
            }
            form.clearErrors("amount");
        }
    }, [watchedPaymentMode, watchedPaymentType, form]);

    const onSubmit = (values: PaymentFormSchema) => {
        initiatePayment(values);
    };

    const formatNaira = (amount: number) =>
        `₦${amount.toLocaleString("en-NG")}`;

    const minInstallment =
        selectedFee && selectedFee.allowsInstallment
            ? selectedFee.amount / 2
            : 0;

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                {/* Academic Year */}
                <FormField
                    control={form.control}
                    name="academic_session"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel className="text-sm font-semibold text-slate-700">
                                Academic Session
                            </FormLabel>
                            <Select onValueChange={field.onChange} value={field.value}>
                                <FormControl>
                                    <SelectTrigger className="h-11 border-slate-200 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500">
                                        <SelectValue placeholder="Select academic session" />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                    {ACADEMIC_YEARS.map((year) => (
                                        <SelectItem key={year} value={year}>
                                            {year} Academic Year
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {/* Semester */}
                <FormField
                    control={form.control}
                    name="academic_semester"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel className="text-sm font-semibold text-slate-700">
                                Semester
                            </FormLabel>
                            <Select onValueChange={field.onChange} value={field.value}>
                                <FormControl>
                                    <SelectTrigger className="h-11 border-slate-200 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500">
                                        <SelectValue placeholder="Select semester" />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                    {SEMESTER_OPTIONS.map((s) => (
                                        <SelectItem key={s.value} value={s.value}>
                                            {s.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {/* Payment Type */}
                <FormField
                    control={form.control}
                    name="payment_type"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel className="text-sm font-semibold text-slate-700">
                                Payment Type
                            </FormLabel>
                            <Select onValueChange={field.onChange} value={field.value}>
                                <FormControl>
                                    <SelectTrigger className="h-11 border-slate-200 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500">
                                        <SelectValue placeholder="Select payment type" />
                                    </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                    {PAYMENT_TYPE_OPTIONS.map((opt) => (
                                        <SelectItem key={opt.value} value={opt.value}>
                                            <div className="flex items-center justify-between gap-4 w-full">
                                                <span>{opt.label}</span>
                                                {FEE_CONFIG[opt.value].amount > 0 && (
                                                    <span className="text-slate-500 text-xs">
                                                        {formatNaira(FEE_CONFIG[opt.value].amount)}
                                                    </span>
                                                )}
                                            </div>
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {/* Fee Info Card */}
                {selectedFee && (
                    <div className="rounded-xl bg-blue-50 border border-blue-100 p-4 flex gap-3">
                        <Info className="h-4 w-4 text-blue-500 mt-0.5 shrink-0" />
                        <div className="space-y-1">
                            <p className="text-sm font-medium text-blue-900">
                                {selectedFee.label}
                                {selectedFee.amount > 0 && (
                                    <span className="ml-2 font-bold">
                                        {formatNaira(selectedFee.amount)}
                                    </span>
                                )}
                            </p>
                            <p className="text-xs text-blue-700">{selectedFee.description}</p>
                            {!selectedFee.allowsInstallment && (
                                <Badge
                                    variant="secondary"
                                    className="text-xs bg-amber-100 text-amber-800 border-amber-200"
                                >
                                    Full payment only
                                </Badge>
                            )}
                            {selectedFee.allowsInstallment && (
                                <Badge
                                    variant="secondary"
                                    className="text-xs bg-green-100 text-green-800 border-green-200"
                                >
                                    Installment available — min {formatNaira(selectedFee.amount / 2)}
                                </Badge>
                            )}
                        </div>
                    </div>
                )}

                {/* Payment Mode — only show for tuition */}
                {watchedPaymentType === "tuition" && (
                    <FormField
                        control={form.control}
                        name="payment_mode"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel className="text-sm font-semibold text-slate-700">
                                    Payment Option
                                </FormLabel>
                                <FormControl>
                                    <RadioGroup
                                        onValueChange={field.onChange}
                                        value={field.value}
                                        className="grid grid-cols-2 gap-3 mt-1"
                                    >
                                        {[
                                            {
                                                value: "FULL",
                                                label: "Pay in Full",
                                                sub: formatNaira(FEE_CONFIG.tuition.amount),
                                            },
                                            {
                                                value: "INSTALLMENT",
                                                label: "Pay Installment",
                                                sub: `Min. ${formatNaira(FEE_CONFIG.tuition.amount / 2)}`,
                                            },
                                        ].map((opt) => (
                                            <Label
                                                key={opt.value}
                                                htmlFor={opt.value}
                                                className={cn(
                                                    "flex flex-col gap-1 rounded-xl border-2 p-4 cursor-pointer transition-all duration-150",
                                                    field.value === opt.value
                                                        ? "border-blue-500 bg-blue-50"
                                                        : "border-slate-200 bg-white hover:border-slate-300"
                                                )}
                                            >
                                                <div className="flex items-center gap-2">
                                                    <RadioGroupItem value={opt.value} id={opt.value} />
                                                    <span className="font-semibold text-sm text-slate-800">
                                                        {opt.label}
                                                    </span>
                                                </div>
                                                <span className="text-xs text-slate-500 ml-6">
                                                    {opt.sub}
                                                </span>
                                            </Label>
                                        ))}
                                    </RadioGroup>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                )}

                {/* Amount */}
                <FormField
                    control={form.control}
                    name="amount"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel className="text-sm font-semibold text-slate-700">
                                Amount (₦)
                            </FormLabel>
                            <FormControl>
                                <div className="relative">
                                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 font-medium text-sm">
                                        ₦
                                    </span>
                                    <Input
                                        {...field}
                                        type="number"
                                        min={0}
                                        disabled={
                                            !allowsInstallment ||
                                            watchedPaymentMode === "FULL" ||
                                            !watchedPaymentType
                                        }
                                        className={cn(
                                            "h-11 pl-8 border-slate-200 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500",
                                            (!allowsInstallment ||
                                                watchedPaymentMode === "FULL") &&
                                            "bg-slate-50 text-slate-600"
                                        )}
                                        value={field.value === 0 ? "" : field.value}
                                        onChange={(e) => {
                                            const val = e.target.value;
                                            field.onChange(val === "" ? 0 : Number(val));
                                        }}
                                        placeholder={
                                            watchedPaymentMode === "INSTALLMENT" && selectedFee
                                                ? `Min. ${formatNaira(minInstallment)}`
                                                : "0"
                                        }
                                    />
                                </div>
                            </FormControl>
                            {watchedPaymentMode === "INSTALLMENT" && selectedFee && (
                                <p className="text-xs text-slate-500 mt-1">
                                    Enter any amount between{" "}
                                    <strong>{formatNaira(minInstallment)}</strong> and{" "}
                                    <strong>{formatNaira(selectedFee.amount)}</strong>. The remainder
                                    becomes your outstanding balance.
                                </p>
                            )}
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {/* Summary */}
                {watchedPaymentType && form.getValues("amount") > 0 && (
                    <div className="rounded-xl border border-slate-200 overflow-hidden">
                        <div className="bg-slate-50 px-4 py-3 border-b border-slate-200">
                            <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                                Payment Summary
                            </p>
                        </div>
                        <div className="p-4 space-y-2 text-sm">
                            <Row label="Payment Type" value={selectedFee?.label ?? ""} />
                            <Row
                                label="Academic Session"
                                value={form.watch("academic_session") || "—"}
                            />
                            <Row
                                label="Semester"
                                value={
                                    SEMESTER_OPTIONS.find(
                                        (s) => s.value === form.watch("academic_semester")
                                    )?.label ?? "—"
                                }
                            />
                            <Row
                                label="Mode"
                                value={watchedPaymentMode === "FULL" ? "Full Payment" : "Installment"}
                            />
                            <Separator className="my-2" />
                            <div className="flex justify-between items-center font-semibold">
                                <span className="text-slate-700">Amount to Pay</span>
                                <span className="text-lg text-blue-700">
                                    {formatNaira(form.watch("amount") || 0)}
                                </span>
                            </div>
                            {watchedPaymentMode === "INSTALLMENT" && selectedFee && (
                                <div className="flex justify-between items-center text-xs text-slate-500">
                                    <span>Remaining balance</span>
                                    <span>
                                        {formatNaira(
                                            selectedFee.amount - (form.watch("amount") || 0)
                                        )}
                                    </span>
                                </div>
                            )}
                        </div>
                    </div>
                )}

                {/* API Error */}
                {error && (
                    <Alert variant="destructive">
                        <AlertCircle className="h-4 w-4" />
                        <AlertDescription>{error.message}</AlertDescription>
                    </Alert>
                )}

                <Button
                    type="submit"
                    disabled={isPending}
                    className="w-full h-12 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-xl transition-all duration-150 shadow-sm shadow-blue-200"
                >
                    {isPending ? (
                        <>
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            Redirecting to Payment...
                        </>
                    ) : (
                        <>
                            <CreditCard className="mr-2 h-4 w-4" />
                            Proceed to Payment
                        </>
                    )}
                </Button>
            </form>
        </Form>
    );
}

// ─── Tiny helper ──────────────────────────────────────────────────────────────
function Row({ label, value }: { label: string; value: string }) {
    return (
        <div className="flex justify-between items-center">
            <span className="text-slate-500">{label}</span>
            <span className="font-medium text-slate-800">{value}</span>
        </div>
    );
}