/* eslint-disable @typescript-eslint/no-unused-vars */
import { LoadingOverlay, Modal, ModalProps, Table } from '@mantine/core';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { getDetailBidHistories } from '../../apis/bid-histories';
import { IBid } from '../../system/type';
import { formatTime } from '../../utils';

export interface IShowHistoriesBidGraysApiModalProps extends ModalProps {
    data: IBid | null;
    onUpdated?: () => void;
}

export default function ShowHistoriesBidPicklesApiModal({ data, onUpdated, ...props }: IShowHistoriesBidGraysApiModalProps) {
    const [histories, setHistories] = useState<Record<string, string>[]>([]);

    const [loading, setLoading] = useState(false);

    const rows = useMemo(() => {
        return histories.map((element, index) => (
            <Table.Tr key={index}>
                <Table.Td>{element['bidderAnonName']}</Table.Td>
                <Table.Td>{element['actualBid']}</Table.Td>
                <Table.Td>{formatTime(new Date(element['bidTimeInMilliSeconds']).toUTCString(), 'HH:mm:ss DD/MM/YYYY')}</Table.Td>
            </Table.Tr>
        ));
    }, [histories]);

    const handleCallApi = useCallback(async () => {
        if (!data?.lot_id) {
            setHistories([]);

            return;
        }

        setLoading(true);
        const response = await getDetailBidHistories(data?.lot_id);
        setLoading(false);

        if (response.data) {
            setHistories(response.data);
        }
    }, [data]);

    useEffect(() => {
        handleCallApi();
    }, [handleCallApi]);

    return (
        <Modal className="relative" {...props} size="xl" title={<span className="text-xl font-bold">BIDDING HISTORY</span>} centered>
            <Table striped highlightOnHover withTableBorder withColumnBorders>
                <Table.Thead>
                    <Table.Tr>
                        <Table.Th>Bidder name</Table.Th>
                        <Table.Th>Actual bid</Table.Th>
                        <Table.Th>Time</Table.Th>
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    {histories.length <= 0 ? (
                        <Table.Tr>
                            <Table.Td colSpan={5} className="text-center">
                                None
                            </Table.Td>
                        </Table.Tr>
                    ) : (
                        rows
                    )}
                </Table.Tbody>
            </Table>

            <LoadingOverlay visible={loading} zIndex={1000} overlayProps={{ blur: 2 }} />
        </Modal>
    );
}
