"use client";
import React, { useState, useEffect } from "react";
import { useGlobalContext } from "@/context/Provider";
import DashboardLayout from "@/components/layout/DashboardLayout";
import apis, { referralUserType } from "@/utils/apis";
import { Copy, User } from "lucide-react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";

interface ReferralSummary {
    referral_code: string;
    number_of_persons: number;
    number_of_orders: number;
    amount: number;
    status: string;
    expired_date: number;
}

interface ReferralHistory {
    child_customer_id: {
        _id: string;
        name: string;
        email: string;
        country_code: string;
        phone: string;
        image: string | null;
    };
    order_count: number;
    createdAt: string;
    updatedAt: string;
}

const Referral = () => {
    const { Toast, userInfo } = useGlobalContext();
    const [referralSummary, setReferralSummary] = useState<ReferralSummary | null>(null);
    const [profileLoading, setProfileLoading] = useState(true);
    const [genLoading, setGenLoading] = useState(false);
    const [referralHistory, setReferralHistory] = useState<ReferralHistory[] | null>(null);
    const [historyLoading, setHistoryLoading] = useState(false);
    const [activeTab, setActiveTab] = useState<referralUserType>(referralUserType.CUSTOMER);

    const fetchProfile = async () => {
        try {
            setProfileLoading(true);
            const res = await apis.Profile.getProfile();
            const data = res?.data?.referral;
            if (data) {
                setReferralSummary({ ...data });
            } else {
                setReferralSummary(null);
            }
        } catch (err) {
            Toast.error(err);
        } finally {
            setProfileLoading(false);
        }
    };

    const fetchReferralHistory = async (type: referralUserType) => {
        try {
            setHistoryLoading(true);
            const res = await apis.Referrals.getUserHistory(type);
            setReferralHistory(res?.data || []);
        } catch (err) {
            Toast.error(err);
        } finally {
            setHistoryLoading(false);
        }
    };

    const handleGenerate = async () => {
        try {
            setGenLoading(true);
            Toast.success("Generating new referral code...");
            await apis.Referrals.getRegenerateCode();
            await fetchProfile();
            Toast.success("Referral code and details updated!");
        } catch (err) {
            Toast.error(err);
        } finally {
            setGenLoading(false);
        }
    };

    useEffect(() => {
        fetchProfile();
    }, []);

    useEffect(() => {
        fetchReferralHistory(activeTab);
    }, [activeTab]);

    const isExpired = referralSummary
        ? new Date(referralSummary.expired_date).setHours(0, 0, 0, 0) <= new Date().setHours(0, 0, 0, 0)
        : true;

    const disableButton = genLoading || profileLoading || !isExpired;

    return (
        <div className="flex flex-col min-h-screen p-5 max-w-7xl mx-auto">
            <div className="w-full space-y-6">
                <h2 className="text-3xl font-semibold text-gray-800">Your Referral</h2>

                {profileLoading ? (
                    <p>Loading referral data...</p>
                ) : userInfo?.appConfiguration?.[0]?.referral?.is_active === false ? (
                    <div className="bg-white p-6 rounded-lg shadow-md text-center py-10 text-gray-600">
                        <p className="text-base font-medium">Referral program is currently not active.</p>
                    </div>
                ) : referralSummary ? (
                    <div className="bg-white p-6 rounded-lg shadow-md space-y-2 text-gray-700 text-sm">
                        <div className="flex items-center gap-2">
                            <strong>Referral Code:</strong>
                            <span className="font-mono text-gray-800">{referralSummary.referral_code}</span>
                            <button
                                onClick={() => {
                                    navigator.clipboard.writeText(referralSummary.referral_code);
                                    Toast.success("Referral code copied!");
                                }}
                                className="text-gray-600 hover:text-black transition"
                                title="Copy to clipboard"
                            >
                                <Copy size={16} className="cursor-pointer" />
                            </button>
                        </div>
                        <div><strong>Total Referrals:</strong> {referralSummary.number_of_persons}</div>
                        <div><strong>Orders via Referrals:</strong> {referralSummary.number_of_orders}</div>
                        <div><strong>Reward Amount:</strong> ${referralSummary.amount}</div>
                        <div><strong>Status:</strong> <span className="capitalize">{referralSummary.status}</span></div>
                        <div>
                            <strong>Expiry Date:</strong>{" "}
                            {new Date(referralSummary.expired_date).toLocaleDateString("en-IN", {
                                day: "numeric", month: "short", year: "numeric",
                            })}
                        </div>
                        <div className="mt-4 p-4 bg-primary/10 border border-primary/30 rounded-md text-primary text-sm">
                            You can refer up to <strong>{referralSummary.number_of_persons}</strong> people. Each person you refer must place at least <strong>{referralSummary.number_of_orders} orders</strong> through their account. Once this condition is met, you will receive a reward amount of <strong>${referralSummary.amount}</strong>.
                        </div>
                        <button
                            onClick={handleGenerate}
                            disabled={disableButton}
                            className={`w-full mt-4 px-5 py-3 text-white font-semibold rounded-md transition ${disableButton
                                ? "bg-primary opacity-50 cursor-not-allowed"
                                : "bg-primary hover:brightness-110 cursor-pointer"
                                }`}
                        >
                            {genLoading ? "Generating..." : "Generate Referral Code"}
                        </button>
                    </div>
                ) : (
                    <p>No referral data available.</p>
                )}


                <div className="mt-8 space-y-4">
                    <h3 className="text-xl font-semibold text-gray-800">Your Referred Users</h3>

                    {/* Tabs */}
                    <div className="flex space-x-2 border-b border-gray-200">
                        {([
                            { label: "Customers", value: referralUserType.CUSTOMER },
                            { label: "Drivers", value: referralUserType.DRIVER },
                            { label: "Restaurants", value: referralUserType.RESTAURANT }
                        ]).map((tab) => {
                            const isActive = activeTab === tab.value;
                            return (
                                <button
                                    key={tab.value}
                                    onClick={() => setActiveTab(tab.value)}
                                    className={`px-4 py-2 text-sm font-semibold transition-all border-b-2 capitalize ${isActive
                                        ? "border-primary text-primary"
                                        : "border-transparent text-gray-500 hover:text-gray-800"
                                        }`}
                                >
                                    {tab.label}
                                </button>
                            );
                        })}
                    </div>

                    {historyLoading ? (
                        <p className="text-gray-500 text-sm py-4">Loading referral history...</p>
                    ) : referralHistory && referralHistory.length > 0 ? (
                        <div className="overflow-x-auto bg-white rounded-lg shadow-md p-4">
                            <table className="min-w-full table-auto border-collapse">
                                <thead>
                                    <tr className="bg-gray-100 text-gray-700">
                                        <th className="px-4 py-2 text-left border-b text-sm">Name</th>
                                        <th className="px-4 py-2 text-left border-b text-sm">Email</th>
                                        {activeTab === referralUserType.CUSTOMER && (
                                            <th className="px-4 py-2 text-left border-b text-sm">Orders Placed</th>
                                        )}
                                        <th className="px-4 py-2 text-left border-b text-sm">Referral Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {referralHistory.map((user, index) => (
                                        <tr
                                            key={user.child_customer_id?._id || index}
                                            className="border-b hover:bg-gray-50 transition"
                                        >
                                            <td className="px-4 py-2 text-sm">
                                                <div className="flex items-center gap-3">
                                                    <Avatar className="h-8 w-8">
                                                        <AvatarImage
                                                            className="object-cover"
                                                            src={user.child_customer_id?.image ? (user.child_customer_id.image.startsWith("http") ? user.child_customer_id.image : `${apis.BUCKET_ROOT}${user.child_customer_id.image}`) : ""}
                                                            alt={user.child_customer_id?.name || "User"}
                                                        />
                                                        <AvatarFallback className="!bg-primary/10 !text-primary text-xs font-semibold">
                                                            {user.child_customer_id?.name ? user.child_customer_id.name.substring(0, 2).toUpperCase() : <User size={14} />}
                                                        </AvatarFallback>
                                                    </Avatar>
                                                    <span>{user.child_customer_id?.name || "N/A"}</span>
                                                </div>
                                            </td>
                                            <td className="px-4 py-2 text-sm">{user.child_customer_id?.email || "N/A"}</td>
                                            {activeTab === referralUserType.CUSTOMER && (
                                                <td className="px-4 py-2 text-sm">{user.order_count}</td>
                                            )}
                                            <td className="px-4 py-2 text-sm">{new Date(user.createdAt).toLocaleDateString()}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    ) : (
                        <p className="text-gray-500 text-sm py-6 bg-white rounded-lg shadow-sm border border-gray-100 text-center">
                            No referrals found for {activeTab}s.
                        </p>
                    )}
                </div>
            </div>
        </div>
    );
};

export default function ReferralPage() {
    return (
        <DashboardLayout>
            <Referral />
        </DashboardLayout>
    );
}


