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

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;
    tax: number;
    total: number;
    status: 'pending' | 'approved' | 'rejected';
    rejected?: {
        by: string;
        at: Date;
        reason: string;
    };
    approved?: {
        by: string;
        at: Date;
    };
}

const WithdrawPending = ({ fetchDataCountWithdraw }: { fetchDataCountWithdraw: () => void }) => {
    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<AffiliateWithdraw[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [isLoading, setIsLoading] = useState(true);

    const [showApproveWithdraw, setShowApproveWithdraw] = useState(false);
    const [showRejectWithdraw, setShowRejectWithdraw] = 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/withdraw-data?page=${page}&per_page=${pageSize}&status=pending`, {
                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 [selectedWithdraw, setSelectedWithdraw] = useState('');

    return (
        <>
            {isMounted && (
                <>
                    <div className="panel border-white-light px-0 pt-0 dark:border-[#1b2e4b]">
                        <div className="user-table">
                            <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: 'affiliate_info',
                                                title: 'Affiliate Info',
                                                render: ({ affiliate_id }) =>
                                                    affiliate_id ? (
                                                        <div>
                                                            <div className="text-sm text-gray-500">{affiliate_id.personal_detail.name}</div>
                                                            <div className="font-semibold hover:no-underline">{affiliate_id.personal_detail.email}</div>
                                                            <div className="text-xs text-gray-400">code : {affiliate_id.affiliate_code}</div>
                                                        </div>
                                                    ) : (
                                                        <div>
                                                            <div className="text-sm text-gray-500">N/A</div>
                                                            <div className="font-semibold hover:no-underline">N/A</div>
                                                        </div>
                                                    ),
                                            },
                                            {
                                                accessor: 'withdraw_number',
                                                title: 'Withdraw Number',
                                                render: ({ withdraw_number }) => <span className="text-xs">{withdraw_number}</span>,
                                            },
                                            {
                                                accessor: 'withdraw_date',
                                                render: ({ withdraw_date }) => (
                                                    <span className="text-xs">
                                                        {new Date(withdraw_date).toLocaleDateString('id-ID', {
                                                            day: 'numeric',
                                                            month: 'numeric',
                                                            year: 'numeric',
                                                        })}
                                                    </span>
                                                ),
                                            },
                                            {
                                                accessor: 'bank_name',
                                                title: 'Bank Account',
                                                render: ({ bank_name, number_bank_account }) => (
                                                    <>
                                                        {bank_name}
                                                        <br />
                                                        {number_bank_account}
                                                    </>
                                                ),
                                            },
                                            {
                                                accessor: 'amount',
                                                title: 'Amount',
                                                render: ({ amount }) => <span className="text-xs">Rp {amount.toLocaleString('id-ID')}</span>,
                                            },
                                            {
                                                accessor: 'tax',
                                                title: 'Tax',
                                                render: ({ tax }) => <span className="text-xs">Rp {tax ? tax.toLocaleString('id-ID') : '0'}</span>,
                                            },
                                            {
                                                accessor: 'fee',
                                                title: 'Service Fee',
                                                render: ({ fee }) => <span className="text-xs">Rp {fee.toLocaleString('id-ID')}</span>,
                                            },
                                            {
                                                accessor: 'total',
                                                title: 'Total',
                                                render: ({ total }) => <span className="text-xs font-bold text-success">Rp {total.toLocaleString('id-ID')}</span>,
                                            },

                                            {
                                                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 }) => (
                                                    <>
                                                        {status === 'pending' && (
                                                            <>
                                                                <div
                                                                    onClick={() => {
                                                                        setShowApproveWithdraw(true);
                                                                        setSelectedWithdraw(id);
                                                                    }}
                                                                    className="btn btn-sm btn-outline-success my-2 cursor-pointer text-xs"
                                                                >
                                                                    Approve
                                                                </div>
                                                                <div
                                                                    onClick={() => {
                                                                        setShowRejectWithdraw(true);
                                                                        setSelectedWithdraw(id);
                                                                    }}
                                                                    className="btn btn-sm btn-outline-danger my-2 cursor-pointer text-xs"
                                                                >
                                                                    Reject
                                                                </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>
                    <ApproveWithdraw
                        selectedWithdraw={selectedWithdraw}
                        show={showApproveWithdraw}
                        closeModal={() => setShowApproveWithdraw(false)}
                        fetchData={fetchData}
                        fetchDataCountTransaction={fetchDataCountWithdraw}
                    />
                    <RejectWithdraw
                        selectedWithdraw={selectedWithdraw}
                        show={showRejectWithdraw}
                        closeModal={() => setShowRejectWithdraw(false)}
                        fetchData={fetchData}
                        fetchDataCountTransaction={fetchDataCountWithdraw}
                    />
                </>
            )}
        </>
    );
};

export default WithdrawPending;
