import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useState, useEffect } from 'react';

interface AffiliateWithdraw {
    id: string;
    affiliate_id: {
        personal_detail: {
            name: string;
            email: string;
        };
        _id: string;
        affiliate_code: string;
    };
    withdraw_number: string;
    withdraw_date: Date;
    bank_name: string;
    number_bank_account: string;
    amount: number;
    fee: number;
    total: number;
    status: 'pending' | 'approved' | 'rejected';
    rejected?: {
        by: string;
        at: Date;
        reason: string;
    };
    approved?: {
        by: string;
        at: Date;
    };
}
interface AffiliatorModalProps {
    isModalOpen: boolean;
    selectedAffiliator: string;
    closeModal: () => void;
}
const AffiliatorWithdrawals = ({ isModalOpen, selectedAffiliator, closeModal }: AffiliatorModalProps) => {
    const [withdrawals, setWithdrawals] = useState<AffiliateWithdraw[]>([]);
    const fetchWithdrawals = async () => {
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/affiliate/affiliate-withdraw/${selectedAffiliator}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
            });
            const { data } = await response.json();
            setWithdrawals(data);
        } catch (error) {
            console.error('Error fetching withdrawals:', error);
        }
    };

    console.log(withdrawals);
    useEffect(() => {
        if (selectedAffiliator) {
            fetchWithdrawals();
        }
    }, [selectedAffiliator]);
    return (
        <>
            <Transition appear show={isModalOpen} as={Fragment}>
                <Dialog as="div" className="relative z-10" onClose={closeModal}>
                    <Transition.Child as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0">
                        <div className="fixed inset-0 bg-[black]/60" />
                    </Transition.Child>

                    <div className="fixed inset-0 overflow-y-auto">
                        <div className="flex min-h-full items-center justify-center p-4 text-center">
                            <Transition.Child
                                as={Fragment}
                                enter="ease-out duration-300"
                                enterFrom="opacity-0 scale-95"
                                enterTo="opacity-100 scale-100"
                                leave="ease-in duration-200"
                                leaveFrom="opacity-100 scale-100"
                                leaveTo="opacity-0 scale-95"
                            >
                                <Dialog.Panel className="panel w-full max-w-4xl overflow-hidden rounded-lg  p-6 text-left text-black dark:text-white-dark ">
                                    <Dialog.Title as="h3" className="mb-4 text-lg font-medium leading-6 text-black dark:text-white-dark">
                                        List of Withdrawals
                                    </Dialog.Title>
                                    <div className="flex flex-col gap-4">
                                        {withdrawals.length > 0 ? (
                                            <div className="max-h-[500px] overflow-x-auto">
                                                <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                                    <thead className="sticky top-0 bg-gray-50 dark:bg-gray-800">
                                                        <tr>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Withdraw Date</th>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Withdraw Number</th>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Bank Account</th>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Amount</th>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Service Fee</th>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Total</th>
                                                            <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-300">Status</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody className="max-h-[500px] divide-y divide-gray-200 overflow-y-scroll bg-white dark:divide-gray-700 dark:bg-gray-900">
                                                        {withdrawals.map((withdrawal) => (
                                                            <tr key={withdrawal.id} className="hover:bg-gray-100 dark:hover:bg-gray-800">
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 dark:text-gray-300">
                                                                    {new Date(withdrawal.withdraw_date).toLocaleDateString('id-ID')}
                                                                </td>
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 dark:text-gray-300">#{withdrawal.withdraw_number}</td>
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 dark:text-gray-300">
                                                                    {withdrawal.bank_name}
                                                                    <br />
                                                                    {withdrawal.number_bank_account}
                                                                </td>
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 dark:text-gray-300">Rp {withdrawal.amount.toLocaleString('id-ID')}</td>
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 dark:text-gray-300">Rp {withdrawal.fee.toLocaleString('id-ID')}</td>
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500 dark:text-gray-300">Rp {withdrawal.total.toLocaleString('id-ID')}</td>
                                                                <td className="whitespace-nowrap px-6 py-4 text-sm text-white">
                                                                    <span
                                                                        className={`rounded-full px-2 py-0.5 text-xs text-white ${
                                                                            withdrawal.status === 'pending' ? 'bg-gray-500' : withdrawal.status === 'approved' ? 'bg-green-500' : 'bg-red-500'
                                                                        }`}
                                                                    >
                                                                        {withdrawal.status}
                                                                    </span>
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        ) : (
                                            <div className="text-center text-gray-500 dark:text-gray-300">No data transactions</div>
                                        )}
                                    </div>
                                </Dialog.Panel>
                            </Transition.Child>
                        </div>
                    </div>
                </Dialog>
            </Transition>
        </>
    );
};

export default AffiliatorWithdrawals;
