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

interface ProductItem {
    product_id: {
        _id: string;
        product_title: string;
    };
    quantity: number;
    price: number;
    _id: string;
}

interface AffiliateTransaction {
    id: string;
    affiliate_id: {
        personal_detail: {
            name: string;
            email: string;
        };
        _id: string;
        affiliate_code: string;
    };
    order_id: string;
    product_items: ProductItem[];
    order_date: string;
    sub_total: number;
    commission: number;
    status: string;
    createdAt: string;
    updatedAt: string;
    __v: number;
    transaction_id: {
        _id: string;
        order_status: string;
    };
    completed: {
        date: string;
        by: {
            _id: string;
            name: string;
        };
    };
}

const TransactionCompleted = () => {
    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<AffiliateTransaction[]>([]);
    const [totalRecords, setTotalRecords] = useState(0);
    const [isLoading, setIsLoading] = useState(true);

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

    const fetchData = async () => {
        setIsLoading(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/affiliate/transaction-data?page=${page}&per_page=${pageSize}&status=completed`, {
                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]);

    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, order_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 className="text-xs text-gray-400">
                                                                order id :{' '}
                                                                <a href={`/orders/edit/${order_id}`} target="_blank" className="text-blue-500 hover:underline">
                                                                    {order_id}
                                                                </a>
                                                            </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: 'product_items',
                                                title: 'Product Items',
                                                render: ({ product_items }) => (
                                                    <>
                                                        {product_items.map((item: ProductItem, index: number) => (
                                                            <span key={index} className="text-xs">
                                                                {item.product_id.product_title} x {item.quantity}
                                                                <br />
                                                            </span>
                                                        ))}
                                                    </>
                                                ),
                                            },
                                            {
                                                accessor: 'sub_total',
                                                title: 'Sub Total / Com',
                                                render: ({ sub_total, commission }) => (
                                                    <span className="text-xs">
                                                        Rp {sub_total.toLocaleString('id-ID')} <br /> <span className="text-green-500">Rp {commission.toLocaleString('id-ID')}</span>
                                                    </span>
                                                ),
                                            },
                                            {
                                                accessor: 'order_date',
                                                render: ({ order_date }) => (
                                                    <span className="text-xs">
                                                        {new Date(order_date).toLocaleDateString('id-ID', {
                                                            day: 'numeric',
                                                            month: 'numeric',
                                                            year: 'numeric',
                                                        })}
                                                    </span>
                                                ),
                                            },
                                            {
                                                accessor: 'order_status',
                                                render: ({ transaction_id }) =>
                                                    transaction_id ? (
                                                        <span className={`text-xs ${transaction_id.order_status === 'Completed' ? 'text-success' : ''}`}>{transaction_id.order_status}</span>
                                                    ) : (
                                                        <span className="text-xs">N/A</span>
                                                    ),
                                            },
                                            {
                                                accessor: 'status',
                                                render: ({ status, completed }) => (
                                                    <div>
                                                        <span
                                                            className={`rounded-full px-2 py-0.5 text-xs text-white ${
                                                                status === 'pending' ? 'bg-gray-500' : status === 'completed' ? 'bg-green-500' : 'bg-red-500'
                                                            }`}
                                                        >
                                                            {status}
                                                        </span>
                                                        {status === 'completed' && (
                                                            <div className="mt-3 text-xs text-gray-400">
                                                                <span>
                                                                    Completed at:{' '}
                                                                    {new Date(completed?.date).toLocaleDateString('id-ID', {
                                                                        day: 'numeric',
                                                                        month: 'numeric',
                                                                        year: 'numeric',
                                                                    })}
                                                                </span>
                                                                <br />
                                                                <span>by {completed?.by.name}</span>
                                                            </div>
                                                        )}
                                                    </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 TransactionCompleted;
