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

interface Affiliate {
    email: string;
    name: string;
    status: string;
    balance: number;
    total_commission: number;
    transactionCount: number;
    withdrawalCount: number;
}

const Dashboard = () => {
    const [isMounted, setIsMounted] = useState(false);

    const [isLoading, setIsLoading] = useState(true);
    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);
    useEffect(() => {
        setIsMounted(true);
    }, []);

    const fetchAffiliates = async () => {
        setIsLoading(true);
        try {
            const response = await fetch(`${process.env.API_URL}api/affiliate/affiliator-dashboard?page=${page}&pageSize=${pageSize}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
            });
            const data = await response.json();

            setRecords(data.data);
            setTotalRecords(data.totalData);
            setPage(data.currentPage);
        } catch (error) {
            console.error('Failed to fetch affiliates:', error);
        } finally {
            setIsLoading(false);
        }
    };

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

    return (
        <>
            {isMounted && (
                <>
                    <div className="panel border-white-light px-0 pt-0 dark:border-[#1b2e4b]">
                        <div className="user-table">
                            <div className="mb-6 px-6">
                                <h2 className="pt-4 text-lg font-semibold">Top Affiliator</h2>
                            </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: 'email',
                                                title: 'Email Address',
                                                render: ({ email }) => <div className="font-semibold hover:no-underline">{email}</div>,
                                            },
                                            {
                                                accessor: 'name',
                                                title: 'Full Name',
                                                render: ({ name }) => <>{name}</>,
                                            },
                                            {
                                                accessor: 'total_commission',
                                                render: ({ total_commission }) => <>Rp {total_commission.toLocaleString('id-ID')}</>,
                                            },
                                            {
                                                accessor: 'balance',
                                                title: 'Current Balance',
                                                render: ({ balance }) => <>Rp {balance.toLocaleString('id-ID')}</>,
                                            },
                                            {
                                                accessor: 'transactionCount',
                                                title: 'Transactions Completed',
                                                render: ({ transactionCount }) => <div className="text-center">{transactionCount} Transactions</div>,
                                            },
                                            {
                                                accessor: 'withdrawalCount',
                                                title: 'Withdrawals Approved',
                                                render: ({ withdrawalCount }) => <div className="text-center">{withdrawalCount} Withdrawals</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>
                </>
            )}
        </>
    );
};

export default Dashboard;
