import { useEffect, useState, Fragment } from 'react';
import 'mantine-datatable/styles.css';
import AffiliatorModal from '@/components/Affiliates/Components/AffiliatorModal';
import AffiliatorTransactions from '@/components/Affiliates/Components/AffiliatorTransactions';
import AffiliatorWithdrawals from '@/components/Affiliates/Components/AffiliatorWithdrawals';
import { DataTable } from '@/components/Shared/DataTable';

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;
    number_bank_account: string;
    image_nik: string;
    image_npwp: string;
    image_bank_account: string;
    account_bank_name: 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;
}

const AffiliateApproved = () => {
    const [isMounted, setIsMounted] = useState(false);
    const [page, setPage] = useState(1);
    const PAGE_SIZES = [5, 10, 20, 30, 50, 100];
    const [pageSize, setPageSize] = useState(PAGE_SIZES[0]);
    const [records, setRecords] = useState<Affiliate[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [search, setSearch] = useState('');
    const [isLoading, setIsLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [selectedAffiliate, setSelectedAffiliate] = useState<Affiliate | null>(null);

    const [isTransactionsModalOpen, setIsTransactionsModalOpen] = useState(false);
    const [isWithdrawalsModalOpen, setIsWithdrawalsModalOpen] = useState(false);

    useEffect(() => {
        setIsMounted(true);
    }, []);

    const fetchData = async () => {
        setIsLoading(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/affiliate/data?page=${page}&per_page=${pageSize}&email=${search}&status=approved`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
            });
            const data = await response.json();
            setPage(data.currentPage);
            setTotalRecords(data.totalData);
            setRecords(data.data);
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, [page, pageSize]);

    const handleKeypress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.key === 'Enter') {
            setPage(1);
            fetchData();
        }
    };

    const openModal = (affiliate: Affiliate) => {
        setSelectedAffiliate(affiliate);
        setIsModalOpen(true);
    };

    const closeModal = () => {
        setIsModalOpen(false);
        setSelectedAffiliate(null);
    };

    const [selectedAffiliator, setSelectedAffiliator] = useState<string>('');
    const openTransactionsModal = (id: string) => {
        setSelectedAffiliator(id);
        setIsTransactionsModalOpen(true);
    };

    const closeTransactionsModal = () => {
        setIsTransactionsModalOpen(false);
        setSelectedAffiliator('');
    };
    const openWithdrawalsModal = (id: string) => {
        setSelectedAffiliator(id);
        setIsWithdrawalsModalOpen(true);
    };
    const closeWithdrawalsModal = () => {
        setIsWithdrawalsModalOpen(false);
        setSelectedAffiliator('');
    };

    return (
        <>
            {isMounted && (
                <>
                    <div className="panel border-white-light px-0 dark:border-[#1b2e4b]">
                        <div className="user-table">
                            <div className="mb-4.5 flex flex-col gap-5 px-5 md:flex-row md:items-center">
                                <div className="flex items-center">
                                    <div className="relative">
                                        <input
                                            type="text"
                                            placeholder="Search by email"
                                            className="peer form-input py-2 ltr:pr-11 rtl:pl-11"
                                            value={search}
                                            onChange={(e) => setSearch(e.target.value)}
                                            onKeyDown={handleKeypress}
                                        />
                                        <div className="absolute top-1/2 -translate-y-1/2 peer-focus:text-primary ltr:right-[11px] rtl:left-[11px]">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <circle cx="11.5" cy="11.5" r="9.5" stroke="currentColor" strokeWidth="1.5" opacity="0.5"></circle>
                                                <path d="M18.5 18.5L22 22" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path>
                                            </svg>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="datatables pagination-padding">
                                {isLoading ? (
                                    <div className="flex justify-center py-4 text-center">
                                        <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>
                                        <span className="ms-3">Please wait, we&apos;re still working to load the data...</span>
                                    </div>
                                ) : (
                                    <DataTable
                                        className="table-hover whitespace-nowrap"
                                        records={records}
                                        minHeight={250}
                                        noRecordsText="No data found"
                                        columns={[
                                            {
                                                accessor: 'personal_detail.email',
                                                title: 'Email Address',
                                                render: ({ personal_detail }) => <div className="font-semibold hover:no-underline">{personal_detail.email}</div>,
                                            },
                                            {
                                                accessor: 'personal_detail.name',
                                                title: 'Full Name',
                                                render: ({ personal_detail }) => <>{personal_detail.name}</>,
                                            },
                                            {
                                                accessor: 'balance',
                                                render: ({ balance }) => <>Rp {balance.toLocaleString('id-ID')}</>,
                                            },
                                            {
                                                accessor: 'createdAt',
                                                title: 'Created At',
                                                render: ({ createdAt }) =>
                                                    createdAt ? (
                                                        <>
                                                            {new Date(createdAt).toLocaleString('id-ID', {
                                                                day: '2-digit',
                                                                month: '2-digit',
                                                                year: 'numeric',
                                                                hour: '2-digit',
                                                                minute: '2-digit',
                                                                second: '2-digit',
                                                            })}
                                                        </>
                                                    ) : (
                                                        <>{'Not available'}</>
                                                    ),
                                            },
                                            {
                                                accessor: 'status',
                                                render: ({ status }) => (
                                                    <span
                                                        className={`rounded-full px-2 py-0.5 text-xs text-white ${
                                                            status === 'pending' ? 'bg-gray-500' : status === 'approved' ? 'bg-green-500' : 'bg-red-500'
                                                        }`}
                                                    >
                                                        {status}
                                                    </span>
                                                ),
                                            },
                                            {
                                                accessor: 'action',
                                                title: '',
                                                render: ({ id, status }) => (
                                                    <div className="flex items-center">
                                                        <button
                                                            className="btn btn-outline-success btn-sm text-xs"
                                                            onClick={() => {
                                                                const affiliate = records.find((record) => record.id === id);
                                                                if (affiliate) openModal(affiliate);
                                                            }}
                                                        >
                                                            Detail
                                                        </button>
                                                        {status === 'approved' && (
                                                            <>
                                                                <button
                                                                    className="btn btn-outline-primary btn-sm ms-2 text-xs"
                                                                    onClick={() => {
                                                                        openTransactionsModal(id);
                                                                    }}
                                                                >
                                                                    Transactions
                                                                </button>
                                                                <button
                                                                    className="btn btn-outline-warning btn-sm ms-2 text-xs"
                                                                    onClick={() => {
                                                                        openWithdrawalsModal(id);
                                                                    }}
                                                                >
                                                                    Withdrawals
                                                                </button>
                                                            </>
                                                        )}
                                                    </div>
                                                ),
                                            },
                                        ]}
                                        highlightOnHover
                                        totalRecords={totalRecords}
                                        recordsPerPage={pageSize}
                                        page={page}
                                        onPageChange={setPage}
                                        recordsPerPageOptions={PAGE_SIZES}
                                        onRecordsPerPageChange={setPageSize}
                                        paginationText={({ from, to, totalRecords }) => `Showing ${from} to ${to} of ${totalRecords}`}
                                    />
                                )}
                            </div>
                        </div>
                    </div>
                    <AffiliatorModal isModalOpen={isModalOpen} selectedAffiliate={selectedAffiliate} closeModal={closeModal} fetchData={fetchData} />
                    <AffiliatorTransactions isModalOpen={isTransactionsModalOpen} selectedAffiliator={selectedAffiliator} closeModal={closeTransactionsModal} />
                    <AffiliatorWithdrawals isModalOpen={isWithdrawalsModalOpen} selectedAffiliator={selectedAffiliator} closeModal={closeWithdrawalsModal} />
                </>
            )}
        </>
    );
};

export default AffiliateApproved;
