import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useState } from 'react';
import Select from 'react-select';
import { coloredToast } from '@/lib/toast';
import { logActivity } from '@/utils/activityLogger';
interface PersonalDetail {
    name: string;
    email: string;
    phone: string;
    gender: 'male' | 'female';
    birthday: string;
    address: string;
    province: string;
    city: string;
    district: string;
    postcode: string;
}

interface IdentityDetail {
    nik: string;
    npwp: string;
    bank_name: string;
    account_bank_name: string;
    number_bank_account: string;
    image_nik: string;
    image_npwp: string;
    image_bank_account: string;
}

interface Rejection {
    reason: string[];
    field: string[];
    date: Date;
    by: {
        name: string;
    };
}

interface Approved {
    date: Date;
    by: {
        name: string;
    };
}

interface Affiliate {
    id: string;
    personal_detail: PersonalDetail;
    identity_detail: IdentityDetail;
    status: 'pending' | 'approved' | 'rejected' | 'to_complete';
    rejected?: Rejection;
    approved?: Approved;
    affiliate_code: string;
    balance: number;
    createdAt?: Date;
    updatedAt?: Date;
}

interface AffiliatorModalProps {
    isModalOpen: boolean;
    selectedAffiliate: Affiliate | null;
    closeModal: () => void;
    fetchData: () => void;
}
const AffiliatorModal = ({ isModalOpen, selectedAffiliate, closeModal, fetchData }: AffiliatorModalProps) => {
    const [isImageModalOpen, setIsImageModalOpen] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string | null>(null);
    const [isLoadingApprove, setIsLoadingApprove] = useState(false);
    const [isRejectModalOpen, setIsRejectModalOpen] = useState(false);
    const [selectedField, setSelectedField] = useState<string[]>([]);
    const [failedReasons, setFailedReasons] = useState<string[]>([]);
    const [isLoadingReject, setIsLoadingReject] = useState(false);

    const [isRejectReasonModalOpen, setIsRejectReasonModalOpen] = useState(false);
    const openImageModal = (imageUrl: string) => {
        setSelectedImage(imageUrl);
        setIsImageModalOpen(true);
    };
    const closeImageModal = () => {
        setIsImageModalOpen(false);
        setSelectedImage(null);
    };

    const handleApprove = async () => {
        setIsLoadingApprove(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/affiliate/approve/${selectedAffiliate?.id}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.message);
            coloredToast('success', 'Affiliate approved successfully');
            await logActivity({
                location: 'Affiliate',
                description: `Affiliate - ${selectedAffiliate?.personal_detail.name} - Berhasil di approve`,
            });
        } catch (error) {
            coloredToast('danger', 'Error approving affiliate');
            await logActivity({
                location: 'Affiliate',
                description: `Affiliate - ${selectedAffiliate?.personal_detail.name} - Gagal di approve`,
            });
            console.error('Error approving affiliate:', error);
        } finally {
            setIsLoadingApprove(false);
            closeModal();
            fetchData();
        }
    };

    const [rejectType, setRejectType] = useState<'reject' | 'to_complete'>('reject');

    const handleReject = async () => {
        if (selectedField.length === 0 || failedReasons.length === 0) {
            coloredToast('warning', 'Please select at least one field and one failed reason');
            return;
        }
        setIsLoadingReject(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/affiliate/reject/${selectedAffiliate?.id}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ field: selectedField, failed: failedReasons, type: rejectType }),
                credentials: 'include',
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.message);
            coloredToast('success', 'Affiliate rejected successfully');
            await logActivity({
                location: 'Affiliate',
                description: `Affiliate - ${selectedAffiliate?.personal_detail.name} - di reject. Failed: ${failedReasons.join(', ')} | Type: ${rejectType}`,
            });
        } catch (error) {
            coloredToast('danger', 'Error rejecting affiliate');
        } finally {
            setIsLoadingReject(false);
            closeModal();
            closeRejectModal();
            fetchData();
        }
    };

    const openRejectModal = (type: 'reject' | 'to_complete') => {
        setRejectType(type);
        setIsRejectModalOpen(true);
    };
    const closeRejectModal = () => {
        setIsRejectModalOpen(false);
        setSelectedField([]);
        setFailedReasons([]);
        setRejectType('reject');
    };
    return (
        <>
            <Transition appear show={isModalOpen} as={Fragment}>
                <Dialog as="div" className="relative z-10" onClose={() => {}}>
                    <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">
                                        Affiliate Details
                                    </Dialog.Title>
                                    <div className="mt-2 space-y-2">
                                        {selectedAffiliate && (
                                            <div className="grid grid-cols-3 gap-4">
                                                {Object.entries(selectedAffiliate.personal_detail).map(([key, value]) => (
                                                    <div key={key}>
                                                        <p className="text-xs text-gray-500">{key.charAt(0).toUpperCase() + key.slice(1)}</p>
                                                        <p className="text-sm font-medium">
                                                            {typeof value === 'string' ? value : new Date(value).toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' })}
                                                        </p>
                                                    </div>
                                                ))}
                                                <div>
                                                    <p className="text-xs text-gray-500">Balance</p>
                                                    <p className="text-sm font-medium">Rp {selectedAffiliate.balance.toLocaleString('id-ID')}</p>
                                                </div>
                                                <div>
                                                    <p className="text-xs text-gray-500">Status</p>
                                                    <p className="text-sm font-medium">{selectedAffiliate.status}</p>
                                                </div>
                                                {Object.keys(selectedAffiliate.identity_detail)
                                                    .sort((a, b) => {
                                                        const order = ['nik', 'npwp', 'bank_name', 'account_bank_name', 'number_bank_account', 'image_nik', 'image_npwp', 'image_bank_account'];
                                                        return order.indexOf(a) - order.indexOf(b);
                                                    })
                                                    .map((key) => {
                                                        const value = selectedAffiliate.identity_detail[key as keyof IdentityDetail]; // Assert key as a keyof IdentityDetail
                                                        return (
                                                            key !== 'number_bank_account' &&
                                                            key !== 'account_bank_name' && (
                                                                <div key={key}>
                                                                    <p className="text-xs text-gray-500">{key === 'bank_name' ? 'BANK ACCOUNT' : key.replace(/_/g, ' ').toUpperCase()}</p>
                                                                    {key === 'bank_name' ? (
                                                                        <p className="text-sm font-medium">
                                                                            {value} - {selectedAffiliate.identity_detail.number_bank_account} <br /> A/n :{' '}
                                                                            {selectedAffiliate.identity_detail.account_bank_name}
                                                                        </p>
                                                                    ) : key.startsWith('image_') && value !== '' ? (
                                                                        <img src={value} alt={key} className="w-50 mt-2 h-20 cursor-pointer object-cover" onClick={() => openImageModal(value)} />
                                                                    ) : (
                                                                        <p className="text-sm font-medium">{value}</p>
                                                                    )}
                                                                </div>
                                                            )
                                                        );
                                                    })}
                                            </div>
                                        )}
                                    </div>

                                    <div className="mt-6 flex items-center justify-between space-x-4">
                                        {selectedAffiliate && (
                                            <>
                                                {selectedAffiliate.status === 'pending' && (
                                                    <div>
                                                        <p className="text-xs text-gray-500"> </p>
                                                        {selectedAffiliate.rejected?.reason && selectedAffiliate.rejected.reason.length > 0 && (
                                                            <>
                                                                <p className="text-xs text-gray-500">Has been Rejected By</p>
                                                                <p className="text-sm font-medium">
                                                                    {selectedAffiliate.rejected?.by?.name} -{' '}
                                                                    {selectedAffiliate.rejected?.date &&
                                                                        new Date(selectedAffiliate.rejected.date).toLocaleDateString('en-GB', {
                                                                            day: '2-digit',
                                                                            month: 'long',
                                                                            year: 'numeric',
                                                                        })}
                                                                </p>
                                                                <div className="flex items-center space-x-2">
                                                                    <p className="text-sm font-medium">Reason:</p>
                                                                    <svg
                                                                        viewBox="0 0 24 24"
                                                                        width="16"
                                                                        height="16"
                                                                        stroke="currentColor"
                                                                        strokeWidth="1.5"
                                                                        fill="none"
                                                                        strokeLinecap="round"
                                                                        strokeLinejoin="round"
                                                                        className="h-4 w-4 cursor-pointer text-gray-500"
                                                                        onClick={() => setIsRejectReasonModalOpen(true)}
                                                                    >
                                                                        <circle cx="12" cy="12" r="10"></circle>
                                                                        <line x1="12" y1="8" x2="12" y2="12"></line>
                                                                        <line x1="12" y1="16" x2="12" y2="16.01"></line>
                                                                    </svg>
                                                                </div>
                                                            </>
                                                        )}
                                                    </div>
                                                )}
                                                {selectedAffiliate.status === 'approved' && (
                                                    <div>
                                                        <p className="text-xs text-gray-500">Approved By</p>
                                                        <p className="text-sm font-medium">
                                                            {selectedAffiliate.approved?.by.name} -{' '}
                                                            {selectedAffiliate.approved?.date &&
                                                                new Date(selectedAffiliate.approved.date).toLocaleDateString('en-GB', {
                                                                    day: '2-digit',
                                                                    month: 'long',
                                                                    year: 'numeric',
                                                                })}
                                                        </p>
                                                    </div>
                                                )}
                                                {selectedAffiliate.status === 'rejected' && (
                                                    <div>
                                                        <p className="text-xs text-gray-500">Rejected By</p>
                                                        <p className="text-sm font-medium">
                                                            {selectedAffiliate.rejected?.by.name} -{' '}
                                                            {selectedAffiliate.rejected?.date &&
                                                                new Date(selectedAffiliate.rejected.date).toLocaleDateString('en-GB', {
                                                                    day: '2-digit',
                                                                    month: 'long',
                                                                    year: 'numeric',
                                                                })}
                                                        </p>
                                                        <div className="flex items-center space-x-2">
                                                            <p className="text-sm font-medium">Reason:</p>
                                                            <svg
                                                                viewBox="0 0 24 24"
                                                                width="16"
                                                                height="16"
                                                                stroke="currentColor"
                                                                strokeWidth="1.5"
                                                                fill="none"
                                                                strokeLinecap="round"
                                                                strokeLinejoin="round"
                                                                className="h-4 w-4 cursor-pointer text-gray-500"
                                                                onClick={() => setIsRejectReasonModalOpen(true)}
                                                            >
                                                                <circle cx="12" cy="12" r="10"></circle>
                                                                <line x1="12" y1="8" x2="12" y2="12"></line>
                                                                <line x1="12" y1="16" x2="12" y2="16.01"></line>
                                                            </svg>
                                                        </div>
                                                    </div>
                                                )}
                                            </>
                                        )}
                                        <div className="flex justify-between space-x-4">
                                            {selectedAffiliate?.status === 'pending' && (
                                                <>
                                                    <button
                                                        type="button"
                                                        disabled={isLoadingApprove}
                                                        className="inline-flex justify-center rounded-md border border-transparent bg-green-600 px-4 py-2 text-xs font-medium text-white hover:bg-green-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-green-500 focus-visible:ring-offset-2"
                                                        onClick={handleApprove}
                                                    >
                                                        {isLoadingApprove ? (
                                                            <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>
                                                        ) : (
                                                            'Set Approved'
                                                        )}
                                                    </button>
                                                    <button
                                                        type="button"
                                                        className="inline-flex justify-center rounded-md border border-transparent bg-red-600 px-4 py-2  text-xs font-medium text-white hover:bg-red-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
                                                        onClick={() => openRejectModal('reject')}
                                                    >
                                                        Set Rejected
                                                    </button>
                                                    <button
                                                        type="button"
                                                        className="inline-flex justify-center rounded-md border border-transparent bg-yellow-600 px-4 py-2  text-xs font-medium text-white hover:bg-yellow-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-yellow-500 focus-visible:ring-offset-2"
                                                        onClick={() => openRejectModal('to_complete')}
                                                    >
                                                        Set To Complete
                                                    </button>
                                                </>
                                            )}
                                            <button
                                                type="button"
                                                className="inline-flex justify-center rounded-md border border-transparent bg-blue-600 px-4 py-2  text-xs font-medium text-white hover:bg-blue-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                                                onClick={closeModal}
                                            >
                                                Close
                                            </button>
                                        </div>
                                    </div>
                                </Dialog.Panel>
                            </Transition.Child>
                        </div>
                    </div>
                </Dialog>
            </Transition>
            <Transition appear show={isImageModalOpen} as={Fragment}>
                <Dialog as="div" className="relative z-10" onClose={() => {}}>
                    <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 bg-opacity-25" />
                    </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="w-full max-w-4xl transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                                    <div className="flex flex-wrap items-center md:flex-nowrap">
                                        <div className="flex-1">{selectedImage && <img src={selectedImage} alt="Preview" className="h-auto max-w-full rounded-lg shadow-lg" />}</div>
                                        {selectedAffiliate && (
                                            <div className="ml-4 mt-2 flex-1">
                                                <h3 className="mb-2 text-lg font-semibold">Personal Details</h3>
                                                <div className="flex flex-col space-y-1">
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">Name:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.name}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">Gender:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.gender}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">Birthday:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.birthday}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">Address:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.address}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">Province:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.province}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">City:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.city}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">District:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.district}</span>
                                                    </div>
                                                    <div className="flex">
                                                        <span className="w-1/4 text-sm font-medium">Postcode:</span>
                                                        <span className="w-3/4 text-sm text-gray-500">{selectedAffiliate.personal_detail.postcode}</span>
                                                    </div>
                                                </div>
                                                <h3 className="mb-2 mt-4 text-lg font-semibold">Identity Details</h3>
                                                <div className="flex">
                                                    <span className="w-1/2 text-sm font-medium">NIK:</span>
                                                    <span className="w-1/2 text-sm text-gray-500">{selectedAffiliate.identity_detail.nik}</span>
                                                </div>
                                                <div className="flex">
                                                    <span className="w-1/2 text-sm font-medium">NPWP:</span>
                                                    <span className="w-1/2 text-sm text-gray-500">{selectedAffiliate.identity_detail.npwp}</span>
                                                </div>
                                                <div className="flex">
                                                    <span className="w-1/2 text-sm font-medium">Bank Name:</span>
                                                    <span className="w-1/2 text-sm text-gray-500">{selectedAffiliate.identity_detail.bank_name}</span>
                                                </div>
                                                <div className="flex">
                                                    <span className="w-1/2 text-sm font-medium">Bank Account Number:</span>
                                                    <span className="w-1/2 text-sm text-gray-500">{selectedAffiliate.identity_detail.number_bank_account}</span>
                                                </div>
                                                <div className="flex">
                                                    <span className="w-1/2 text-sm font-medium">Bank Account Name:</span>
                                                    <span className="w-1/2 text-sm text-gray-500">{selectedAffiliate.identity_detail.account_bank_name}</span>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                    <div className="mt-4">
                                        <button
                                            type="button"
                                            className="inline-flex justify-center rounded-md border border-transparent bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                                            onClick={closeImageModal}
                                        >
                                            Close
                                        </button>
                                    </div>
                                </Dialog.Panel>
                            </Transition.Child>
                        </div>
                    </div>
                </Dialog>
            </Transition>
            <Transition appear show={isRejectModalOpen} as={Fragment}>
                <Dialog as="div" className="relative z-10" onClose={() => {}}>
                    <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 bg-opacity-25 " />
                    </Transition.Child>

                    <div className="fixed inset-0 overflow-y-scroll">
                        <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 h-[400px] w-1/2 max-w-4xl overflow-hidden rounded-lg border-2 p-6 text-left text-black dark:border-white-dark  dark:text-white-dark">
                                    <Dialog.Title as="h3" className="mb-4 text-lg font-medium leading-6 text-black dark:text-white-dark">
                                        {rejectType === 'reject' ? 'Rejection Reason' : 'To Complete Reason'}
                                    </Dialog.Title>
                                    <div className="custom-select mt-2">
                                        <label htmlFor="field" className="block text-sm font-medium text-gray-700">
                                            Reason
                                        </label>
                                        {typeof window !== 'undefined' && (
                                            <Select
                                                placeholder="Select reasons"
                                                options={[
                                                    {
                                                        value: 'Nama tidak sesuai dengan dokumen yang disertakan.',
                                                        label: 'Nama tidak sesuai dengan dokumen yang disertakan.',
                                                    },
                                                    { value: 'Nomor telepon tidak terdaftar.', label: 'Nomor telepon tidak terdaftar.' },
                                                    { value: 'Alamat tidak lengkap atau tidak akurat.', label: 'Alamat tidak lengkap atau tidak akurat.' },
                                                    { value: 'Kode pos tidak sesuai.', label: 'Kode pos tidak sesuai.' },
                                                    {
                                                        value: 'Nomor identitas tidak cocok dengan gambar / foto yang disertakan.',
                                                        label: 'Nomor identitas tidak cocok dengan gambar / foto yang disertakan.',
                                                    },
                                                    { value: 'Lengkapi nomor identitas / KTP', label: 'Lengkapi nomor identitas / KTP' },
                                                    { value: 'Nomor NPWP tidak cocok dengan gambar / foto NPWP.', label: 'Nomor NPWP tidak cocok dengan gambar / foto NPWP.' },
                                                    { value: 'Lengkapi nomor NPWP', label: 'Lengkapi nomor NPWP' },
                                                    {
                                                        value: 'Nomor rekening bank tidak cocok dengan gambar / foto buku rekening.',
                                                        label: 'Nomor rekening bank tidak cocok dengan gambar / foto buku rekening.',
                                                    },
                                                    { value: 'Lengkapi nomor rekening bank', label: 'Lengkapi nomor rekening bank' },
                                                    { value: 'Nomor rekening bank tidak terdaftar.', label: 'Nomor rekening bank tidak terdaftar.' },
                                                    { value: 'Bank tidak terdaftar.', label: 'Bank tidak terdaftar.' },
                                                    { value: 'Lengkapi nama bank', label: 'Lengkapi nama bank' },
                                                    { value: 'Nama pemilik rekening bank tidak sesuai.', label: 'Nama pemilik rekening bank tidak sesuai.' },
                                                    { value: 'Lengkapi nama pemilik rekening bank', label: 'Lengkapi nama pemilik rekening bank' },
                                                    { value: 'Gambar / Foto KTP kurang jelas atau tidak fokus.', label: 'Gambar / Foto KTP kurang jelas atau tidak fokus.' },
                                                    { value: 'Gambar / Foto KTP tidak sesuai.', label: 'Gambar / Foto KTP tidak sesuai.' },
                                                    { value: 'Lengkapi Gambar / Foto KTP', label: 'Lengkapi Gambar / Foto KTP' },
                                                    { value: 'Gambar / Foto NPWP kurang jelas atau tidak fokus.', label: 'Gambar / Foto NPWP kurang jelas atau tidak fokus.' },
                                                    { value: 'Gambar / Foto NPWP tidak sesuai.', label: 'Gambar / Foto NPWP tidak sesuai.' },
                                                    { value: 'Lengkapi Gambar / Foto NPWP', label: 'Lengkapi Gambar / Foto NPWP' },
                                                    {
                                                        value: 'Gambar / Foto buku rekening bank kurang jelas atau tidak fokus.',
                                                        label: 'Gambar / Foto buku rekening bank kurang jelas atau tidak fokus.',
                                                    },
                                                    { value: 'Gambar / Foto buku rekening bank tidak sesuai.', label: 'Gambar / Foto buku rekening bank tidak sesuai.' },
                                                    { value: 'Lengkapi Gambar / Foto Buku Rekening Bank', label: 'Lengkapi Gambar / Foto Buku Rekening Bank' },
                                                ]}
                                                value={failedReasons.map((reason) => ({ value: reason, label: reason }))}
                                                onChange={(selectedOptions: any) => setFailedReasons(selectedOptions.map((option: any) => option.value))}
                                                className="w-full"
                                                isMulti
                                                menuPortalTarget={document.body} // Ensure the dropdown menu is rendered in the body
                                                styles={{ menuPortal: (base: any) => ({ ...base, zIndex: 9999 }) }} // Adjust the z-index if necessary
                                            />
                                        )}
                                    </div>
                                    <div className="custom-select mt-2">
                                        <label htmlFor="field" className="block text-sm font-medium text-gray-700">
                                            Field
                                        </label>
                                        {typeof window !== 'undefined' && (
                                            <Select
                                                id="field"
                                                name="field"
                                                className="w-full"
                                                value={selectedField.map((field: any) => ({ value: field, label: field }))}
                                                onChange={(selectedOptions: any) => setSelectedField(selectedOptions.map((option: any) => option.value))}
                                                options={[
                                                    { value: 'name', label: 'Name' },
                                                    { value: 'phone', label: 'Phone' },
                                                    { value: 'address', label: 'Address' },
                                                    { value: 'postcode', label: 'Postcode' },
                                                    { value: 'nik', label: 'Identity Number' },
                                                    { value: 'npwp', label: 'NPWP Number' },
                                                    { value: 'number_bank_account', label: 'Bank Account Number' },
                                                    { value: 'account_bank_name', label: 'Bank Account Name' },
                                                    { value: 'bank_name', label: 'Bank Name' },
                                                    { value: 'image_nik', label: 'NIK Image' },
                                                    { value: 'image_npwp', label: 'NPWP Image' },
                                                    { value: 'image_bank_account', label: 'Bank Account Image' },
                                                ]}
                                                isMulti
                                                menuPortalTarget={document.body} // Ensure the dropdown menu is rendered in the body
                                                styles={{ menuPortal: (base: any) => ({ ...base, zIndex: 9999 }) }} // Adjust the z-index if necessary
                                            />
                                        )}
                                    </div>

                                    <div className="mt-4 flex justify-end space-x-2">
                                        <button
                                            type="button"
                                            className="inline-flex justify-center rounded-md border border-transparent bg-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-500 focus-visible:ring-offset-2"
                                            onClick={closeRejectModal}
                                        >
                                            Cancel
                                        </button>
                                        <button
                                            type="button"
                                            disabled={isLoadingReject}
                                            className={`inline-flex justify-center rounded-md border border-transparent px-4 py-2 text-sm font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 ${
                                                rejectType === 'reject' ? 'bg-red-600 text-white hover:bg-red-700' : 'bg-yellow-600 text-black hover:bg-yellow-700'
                                            }`}
                                            onClick={handleReject}
                                        >
                                            {isLoadingReject ? (
                                                <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>
                                            ) : rejectType === 'reject' ? (
                                                'Reject'
                                            ) : (
                                                'To Complete'
                                            )}
                                        </button>
                                    </div>
                                </Dialog.Panel>
                            </Transition.Child>
                        </div>
                    </div>
                </Dialog>
            </Transition>
            <Transition appear show={isRejectReasonModalOpen} as={Fragment}>
                <Dialog as="div" className="relative z-10" onClose={() => {}}>
                    <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 bg-opacity-25" />
                    </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="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                                    <Dialog.Title as="h3" className="text-lg font-medium leading-6 text-gray-900">
                                        Rejection Reason
                                    </Dialog.Title>
                                    <div className="mt-2">
                                        <ul className="list-inside list-disc text-sm text-gray-500">
                                            {selectedAffiliate?.rejected?.reason?.map((reason, index) => (
                                                <li key={index}>{reason}</li>
                                            ))}
                                        </ul>
                                    </div>

                                    <div className="mt-4">
                                        <button
                                            type="button"
                                            className="text-blue-9000 inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
                                            onClick={() => setIsRejectReasonModalOpen(false)}
                                        >
                                            Close
                                        </button>
                                    </div>
                                </Dialog.Panel>
                            </Transition.Child>
                        </div>
                    </div>
                </Dialog>
            </Transition>
        </>
    );
};

export default AffiliatorModal;
