import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useState } from 'react';
import { coloredToast } from '@/lib/toast';
import { logActivity } from '@/utils/activityLogger';
const ApproveWithdraw = ({
    show,
    selectedWithdraw,
    closeModal,
    fetchData,
    fetchDataCountTransaction,
}: {
    show: boolean;
    selectedWithdraw: string;
    closeModal: () => void;
    fetchData: () => void;
    fetchDataCountTransaction: () => void;
}) => {
    const [isLoading, setIsLoading] = useState(false);

    const handleApproveWithdraw = async () => {
        setIsLoading(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/affiliate/approve-withdraw/${selectedWithdraw}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
            });

            if (!response.ok) {
                throw new Error('Failed to complete transaction');
            }

            const data = await response.json();
            console.log('Transaction completed:', data);
            await logActivity({
                location: 'Affiliate',
                description: `Affiliate - ${selectedWithdraw} - Berhasil di approve`,
            });
        } catch (error) {
            console.error('Error completing transaction:', error);
            await logActivity({
                location: 'Affiliate',
                description: `Affiliate - ${selectedWithdraw} - Gagal di approve`,
            });
            coloredToast('error', 'Failed to complete transaction');
        }
        setIsLoading(false);
        closeModal();
        fetchData();
        fetchDataCountTransaction();
    };

    return (
        <Transition appear show={show} as={Fragment}>
            <Dialog as="div" className="relative z-10" onClose={closeModal}>
                <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"
                >
                    <div className="fixed inset-0 bg-black bg-opacity-25 transition-opacity" />
                </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-md transform overflow-hidden rounded-2xl p-6 text-left align-middle text-black shadow-xl transition-all dark:text-white-dark">
                                <Dialog.Title as="h3" className="text-lg font-medium leading-6  text-black dark:text-white-dark">
                                    Approve Withdraw
                                </Dialog.Title>
                                <div className="mt-2">
                                    <p className="text-sm text-gray-500">Are you sure you want to approve the withdraw?</p>
                                </div>

                                <div className="mt-4 flex align-bottom">
                                    <button
                                        type="button"
                                        className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                                        onClick={handleApproveWithdraw}
                                        disabled={isLoading}
                                    >
                                        {isLoading ? (
                                            <svg
                                                viewBox="0 0 24 24"
                                                width="24"
                                                height="24"
                                                stroke="currentColor"
                                                strokeWidth="1.5"
                                                fill="none"
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                className="h-5 w-5 animate-spin text-white-dark"
                                            >
                                                <line x1="12" y1="2" x2="12" y2="6"></line>
                                                <line x1="12" y1="18" x2="12" y2="22"></line>
                                                <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                                <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                                <line x1="2" y1="12" x2="6" y2="12"></line>
                                                <line x1="18" y1="12" x2="22" y2="12"></line>
                                                <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                                <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                                            </svg>
                                        ) : (
                                            'Yes'
                                        )}
                                    </button>
                                    <button
                                        type="button"
                                        className="ml-2 inline-flex justify-center rounded-md border border-transparent bg-red-100 px-4 py-2 text-sm font-medium text-red-900 hover:bg-red-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
                                        onClick={closeModal}
                                    >
                                        No
                                    </button>
                                </div>
                            </Dialog.Panel>
                        </Transition.Child>
                    </div>
                </div>
            </Dialog>
        </Transition>
    );
};

export default ApproveWithdraw;
