"use client";
import React, { useEffect, useState, Suspense } from "react";
import { useRouter, useParams } from "next/navigation";
import { CheckCircle2, XCircle, Loader2 } from "lucide-react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import apis from "@/utils/apis";
import { PaymentStatus } from "@/types";

const PaymentCallbackContent = () => {
    const router = useRouter();
    const params = useParams();
    const id = params.id as string;

    const [loading, setLoading] = useState(true);
    const [status, setStatus] = useState<PaymentStatus | null>(null);
    const [paymentData, setPaymentData] = useState<any>(null);

    const fetchPaymentDetails = async () => {
        try {
            const res = await apis.PayTab.getPaymentDetails(id);
            if (res?.payment) {
                setPaymentData(res.payment);
                setStatus(res.payment.payment_status as PaymentStatus);
            }
        } catch (err) {
            console.error("Error fetching payment details:", err);
            setStatus(PaymentStatus.Failed);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (id) {
            fetchPaymentDetails();
        }
    }, [id]);

    useEffect(() => {
        if (!loading && status) {
            const timeout = setTimeout(() => {
                if (status === PaymentStatus.Complete) {
                    if (paymentData?.paymentFor === "wallet") {
                        router.push("/wallet");
                    } else if (paymentData?.paymentFor === "slot" || paymentData?.paymentFor === "dineout" || paymentData?.booking_id) {
                        router.push("/dineout-list");
                    } else if (paymentData?.paymentFor === "catering" || paymentData?.catering_id) {
                        router.push("/catering-list");
                    } else if (!paymentData?.order_id) {
                        router.push("/wallet");
                    } else {
                        router.push("/myorders?page=1&limit=10");
                    }
                } else {
                    if (paymentData?.paymentFor === "slot" || paymentData?.paymentFor === "dineout" || paymentData?.booking_id) {
                        router.push("/dineout-list");
                    } else if (paymentData?.paymentFor === "catering" || paymentData?.catering_id) {
                        router.push("/catering-list");
                    } else {
                        router.push("/wallet");
                    }
                }
            }, 3000);

            return () => clearTimeout(timeout);
        }
    }, [loading, status, paymentData, router]);

    if (loading) {
        return (
            <div className="flex flex-col items-center justify-center min-h-[60vh]">
                <Loader2 className="w-12 h-12 text-primary animate-spin mb-4" />
                <p className="text-gray-600">Verifying your payment...</p>
            </div>
        );
    }

    const isSuccess = status === PaymentStatus.Complete;

    return (
        <div className="flex flex-col items-center justify-center min-h-[60vh] p-4 text-center">
            {isSuccess ? (
                <>
                    <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mb-6">
                        <CheckCircle2 className="w-12 h-12 text-green-600" />
                    </div>
                    <h1 className="text-3xl font-bold text-gray-900 mb-2">Payment Successful!</h1>
                    <p className="text-gray-600 mb-8">
                        Your transaction has been processed successfully.
                        {paymentData?.paytab_transaction_id && <span className="block mt-1 text-sm">Ref: {paymentData.paytab_transaction_id}</span>}
                    </p>
                    <p className="text-sm text-gray-500 animate-pulse">
                        Redirecting you back to the app...
                    </p>
                </>
            ) : (
                <>
                    <div className="w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mb-6">
                        <XCircle className="w-12 h-12 text-red-600" />
                    </div>
                    <h1 className="text-3xl font-bold text-gray-900 mb-2">Payment {status === PaymentStatus.Declined ? "Declined" : "Failed"}</h1>
                    <p className="text-gray-600 mb-8">
                        {status === PaymentStatus.Declined
                            ? "Your payment was declined by the provider. Please try another method."
                            : "There was an issue processing your payment. Please try again."}
                    </p>
                    <button
                        onClick={() => {
                            if (paymentData?.paymentFor === "slot" || paymentData?.paymentFor === "dineout" || paymentData?.booking_id) {
                                router.push("/dineout-list");
                            } else if (paymentData?.paymentFor === "catering" || paymentData?.catering_id) {
                                router.push("/catering-list");
                            } else {
                                router.push("/wallet");
                            }
                        }}
                        className="bg-primary text-white px-6 py-2 rounded-md font-medium"
                    >
                        {paymentData?.paymentFor === "slot" || paymentData?.paymentFor === "dineout" || paymentData?.booking_id
                            ? "Go to DineOut List"
                            : paymentData?.paymentFor === "catering" || paymentData?.catering_id
                                ? "Go to Catering List"
                                : "Go to Wallet"}
                    </button>
                </>
            )}
        </div>
    );
};

export default function PaymentCallbackPage() {
    return (
        <DashboardLayout>
            <Suspense fallback={<div className="flex items-center justify-center min-h-screen">Loading...</div>}>
                <PaymentCallbackContent />
            </Suspense>
        </DashboardLayout>
    );
}
