"use client";

import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
    CheckCircle2,
    XCircle,
    Loader2,
    RefreshCw,
    LayoutDashboard,
    AlertCircle,
    Clock,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useVerifyPayment } from "../hooks/use-verify-payment";

interface PaymentVerificationProps {
    transRef: string;
}

export function PaymentVerification({ transRef }: PaymentVerificationProps) {
    const router = useRouter();

    const { data, isLoading, isError, error, refetch, isFetching } =
        useVerifyPayment(transRef);
    console.log("data verify", data);

    const isSuccessful = data?.payment_status === "successful"; //|| data?.payment_status === 200;
    const isPending = data?.payment_status === "pending";
    const isConfirmed = data?.payment_status === "confirmed";
    const isFailed = data?.payment_status === "failed";

    const handleRetry = () => {
        refetch();
    };

    const handleContinue = () => {
        router.push("/dashboard/student");
    };

    // ── Loading state ──────────────────────────────────────────────────────────
    if (isLoading || isFetching) {
        return (
            <VerificationCard>
                <StatusIcon
                    icon={<Loader2 className="h-10 w-10 text-blue-500 animate-spin" />}
                    bg="bg-blue-50"
                />
                <h2 className="text-xl font-bold text-slate-900 mt-5">
                    Verifying your payment…
                </h2>
                <p className="text-sm text-slate-500 mt-2 max-w-xs text-center">
                    Please wait while we confirm your transaction with our payment
                    gateway. This usually takes a few seconds.
                </p>
                <div className="mt-6 w-full max-w-xs">
                    <TransRefBadge transRef={transRef} />
                </div>
            </VerificationCard>
        );
    }

    // ── Network / API error ────────────────────────────────────────────────────
    if (isError) {
        return (
            <VerificationCard>
                <StatusIcon
                    icon={<XCircle className="h-10 w-10 text-red-500" />}
                    bg="bg-red-50"
                />
                <h2 className="text-xl font-bold text-slate-900 mt-5">
                    Verification Failed
                </h2>
                <p className="text-sm text-slate-500 mt-2 max-w-xs text-center">
                    We couldn't reach the payment server. Please check your connection and
                    try again.
                </p>
                <Alert variant="destructive" className="mt-4 text-left max-w-xs">
                    <AlertCircle className="h-4 w-4" />
                    <AlertDescription className="text-xs">
                        {(error as Error)?.message ?? "An unexpected error occurred."}
                    </AlertDescription>
                </Alert>
                <div className="mt-6 w-full max-w-xs space-y-3">
                    <TransRefBadge transRef={transRef} />
                    <Button
                        onClick={handleRetry}
                        variant="outline"
                        className="w-full h-11 font-semibold border-2 hover:bg-slate-50"
                    >
                        <RefreshCw className="mr-2 h-4 w-4" />
                        Retry Verification
                    </Button>
                </div>
            </VerificationCard>
        );
    }

    // ── Gateway-level failure ──────────────────────────────────────────────────
    if (isFailed) {
        return (
            <VerificationCard>
                <StatusIcon
                    icon={<XCircle className="h-10 w-10 text-red-500" />}
                    bg="bg-red-50"
                />
                <h2 className="text-xl font-bold text-slate-900 mt-5">
                    Payment Failed
                </h2>
                <p className="text-sm text-slate-500 mt-2 max-w-xs text-center">
                    {data?.message ??
                        "Your payment was not successful. If you were charged, please contact the finance office."}
                </p>
                <div className="mt-6 w-full max-w-xs space-y-3">
                    <TransRefBadge transRef={transRef} />
                    <Button
                        onClick={handleRetry}
                        variant="outline"
                        className="w-full h-11 font-semibold border-2 hover:bg-slate-50"
                    >
                        <RefreshCw className="mr-2 h-4 w-4" />
                        Check Again
                    </Button>
                </div>
            </VerificationCard>
        );
    }

    // ── Pending state ──────────────────────────────────────────────────────────
    if (isPending) {
        return (
            <VerificationCard>
                <StatusIcon
                    icon={<Clock className="h-10 w-10 text-amber-500" />}
                    bg="bg-amber-50"
                />
                <h2 className="text-xl font-bold text-slate-900 mt-5">
                    Payment Pending
                </h2>
                <p className="text-sm text-slate-500 mt-2 max-w-xs text-center">
                    Your payment is being processed. This can take a moment. Click retry
                    to check again.
                </p>
                <div className="mt-6 w-full max-w-xs space-y-3">
                    <TransRefBadge transRef={transRef} />
                    <Button
                        onClick={handleRetry}
                        disabled={isFetching}
                        variant="outline"
                        className="w-full h-11 font-semibold border-2 hover:bg-slate-50"
                    >
                        {isFetching ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                            <RefreshCw className="mr-2 h-4 w-4" />
                        )}
                        Retry
                    </Button>
                </div>
            </VerificationCard>
        );
    }

    // ── Confirmed state (gateway acknowledged, awaiting finalization) ──────────
    if (isConfirmed) {
        return (
            <VerificationCard>
                <StatusIcon
                    icon={<CheckCircle2 className="h-10 w-10 text-indigo-600" />}
                    bg="bg-indigo-50"
                />
                <h2 className="text-xl font-bold text-red-700 mt-5">Payment Already Confirmed</h2>
                <p className="text-sm text-slate-500 mt-2 max-w-xs text-center">
                    The payment gateway has confirmed the transaction. Your account will be
                    updated shortly — you may continue to your dashboard.
                </p>

                {/* Payment details */}
                {data && (
                    <div className="mt-5 w-full max-w-xs rounded-xl border border-slate-200 overflow-hidden text-sm">
                        <div className="bg-slate-50 px-4 py-2 border-b border-slate-200">
                            <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">
                                Transaction Details
                            </p>
                        </div>
                        <div className="px-4 py-3 space-y-2">
                            <DetailRow label="Reference" value={data.meta.transRef} mono />
                            <DetailRow
                                label="Amount"
                                value={`₦${data.meta.amount?.toLocaleString("en-NG") ?? "—"}`}
                            />
                            <DetailRow label="Type" value={data.meta.payment_type ?? "—"} />
                            {data.meta.paid_at && (
                                <DetailRow
                                    label="Paid At"
                                    value={new Date(data.meta.paid_at).toLocaleString("en-NG", {
                                        dateStyle: "medium",
                                        timeStyle: "short",
                                    })}
                                />
                            )}
                        </div>
                    </div>
                )}

                <div className="mt-6 w-full max-w-xs">
                    <Button
                        onClick={handleContinue}
                        className="w-full h-12 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-xl shadow-sm shadow-indigo-200 transition-all duration-150"
                    >
                        <LayoutDashboard className="mr-2 h-4 w-4" />
                        Continue to Dashboard
                    </Button>
                </div>
            </VerificationCard>
        );
    }

    // ── Success ────────────────────────────────────────────────────────────────
    if (isSuccessful) {
        return (
            <VerificationCard>
                {/* Animated success ring */}
                <div className="relative">
                    <div className="h-20 w-20 rounded-full bg-green-50 flex items-center justify-center">
                        <div className="h-16 w-16 rounded-full bg-green-100 flex items-center justify-center animate-in zoom-in-50 duration-500">
                            <CheckCircle2 className="h-9 w-9 text-green-600" />
                        </div>
                    </div>
                    <div className="absolute inset-0 rounded-full border-2 border-green-200 animate-ping opacity-30" />
                </div>

                <h2 className="text-xl font-bold text-slate-900 mt-5">
                    Payment Successful!
                </h2>
                <p className="text-sm text-slate-500 mt-2 max-w-xs text-center">
                    Your payment has been confirmed. Your records will be updated
                    shortly.
                </p>

                {/* Payment details */}
                {data && (
                    <div className="mt-5 w-full max-w-xs rounded-xl border border-slate-200 overflow-hidden text-sm">
                        <div className="bg-slate-50 px-4 py-2 border-b border-slate-200">
                            <p className="text-xs font-semibold uppercase tracking-wider text-slate-400">
                                Transaction Details
                            </p>
                        </div>
                        <div className="px-4 py-3 space-y-2">
                            <DetailRow label="Reference" value={data.meta?.transRef ?? "—"} mono />
                            <DetailRow
                                label="Amount"
                                value={`₦${data.meta?.amount?.toLocaleString("en-NG") ?? "—"}`}
                            />
                            <DetailRow label="Type" value={data.meta?.payment_type ?? "—"} />
                            {data.meta?.paid_at && (
                                <DetailRow
                                    label="Paid At"
                                    value={new Date(data.meta.paid_at).toLocaleString("en-NG", {
                                        dateStyle: "medium",
                                        timeStyle: "short",
                                    })}
                                />
                            )}
                        </div>
                    </div>
                )}

                <div className="mt-6 w-full max-w-xs">
                    <Button
                        onClick={handleContinue}
                        className="w-full h-12 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-xl shadow-sm shadow-green-200 transition-all duration-150"
                    >
                        <LayoutDashboard className="mr-2 h-4 w-4" />
                        Go to Dashboard
                    </Button>
                </div>
            </VerificationCard>
        );
    }

    return null;
}

// ─── Sub-components ────────────────────────────────────────────────────────────

function VerificationCard({ children }: { children: React.ReactNode }) {
    return (
        <div className="flex flex-col items-center justify-center py-10 px-6">
            {children}
        </div>
    );
}

function StatusIcon({
    icon,
    bg,
}: {
    icon: React.ReactNode;
    bg: string;
}) {
    return (
        <div
            className={cn(
                "h-20 w-20 rounded-full flex items-center justify-center",
                bg
            )}
        >
            {icon}
        </div>
    );
}

function TransRefBadge({ transRef }: { transRef: string }) {
    return (
        <div className="flex items-center justify-between rounded-lg bg-slate-50 border border-slate-200 px-3 py-2">
            <span className="text-xs text-slate-500">Transaction Ref</span>
            <span className="text-xs font-mono font-medium text-slate-700 truncate max-w-[160px]">
                {transRef}
            </span>
        </div>
    );
}

function DetailRow({
    label,
    value,
    mono = false,
}: {
    label: string;
    value: string;
    mono?: boolean;
}) {
    return (
        <div className="flex justify-between items-center">
            <span className="text-slate-500 text-xs">{label}</span>
            <span
                className={cn(
                    "text-slate-800 font-medium text-xs",
                    mono && "font-mono"
                )}
            >
                {value}
            </span>
        </div>
    );
}