'use client';

import Loader from '@/components/common/Loader';
import { Scrollbar } from '@/components/common/Scrollbar';
import { box_requests } from '@/data/box/box.requests';
import { Box, styled, SxProps, Table, TableBody, TableCell, TableHead, TableRow, Theme } from '@mui/material';
import React from 'react';

export interface ColumnData<Data, DataKey = keyof Data> {
    dataKey?: DataKey;
    label: string;
    width: string | number;
    numeric?: boolean;
    getSxStyles?: (data: Data) => SxProps<Theme>;
    renderCell?: (data: Data, rowIndex: number) => React.ReactNode;
    renderHeaderCell?: (rowIndex: number) => React.ReactNode;
}

const StyledTable = styled(Table)`
    td,
    th {
        height: auto;
        padding: 12px 24px;
        border-color: #ebeff6;
        flex-shrink: 0;
    }

    tr {
        &:last-child {
            td {
                border-color: transparent;
            }
        }
    }

    thead {
        th {
            font-size: 16px;
            font-weight: 500;
            line-height: 20px;
            color: #8c959e;
        }
    }

    tbody {
        td {
            font-size: 15px;
            font-weight: 600;
            line-height: 20px;
            color: #000;
        }
    }
`;

const StyledTableRow = styled(TableRow)``;
const StyledTableCell = styled(TableCell)`
    flex-shrink: 0;
`;

type Props<Data> = {
    columns: ColumnData<Data & { id: number | string }>[];
    data: Data[];
    loading: boolean;
    onClickRow?: (data: Data) => void;
    color?: string;
};

const MyTable = <Data extends { id: number | string }>(props: Props<Data>) => {
    const { columns, data, loading, onClickRow } = props;

    const isEmpty = !data?.length && !loading;

    const [boxStatuses, setBoxStatuses] = React.useState<Record<string, boolean>>({});

    React.useEffect(() => {
        const fetchBoxStatuses = async () => {
            const statuses: Record<string, boolean> = {};

            await Promise.all(
                data.map(async row => {
                    try {
                        const res = await box_requests.find({ packetId: row.id });
                        const boxData = res.data.data;

                        const total = boxData.items.reduce(
                            (acc: { totalAmount: number; totalAccepted: number }, item: any) => {
                                acc.totalAmount += +item.amount || 0;
                                acc.totalAccepted += +item.acceptedNumber || 0;
                                return acc;
                            },
                            { totalAmount: 0, totalAccepted: 0 }
                        );

                        statuses[row.id] = total.totalAmount === total.totalAccepted;
                    } catch (error) {
                        console.error('Error fetching box status:', error);
                        statuses[row.id] = false;
                    }
                })
            );

            setBoxStatuses(statuses);
        };

        if (!loading && data.length > 0) {
            fetchBoxStatuses();
        }
    }, [data, loading]);

    return (
        <Box>
            <Scrollbar>
                <StyledTable>
                    <TableHead>
                        <StyledTableRow>
                            {columns.map((column, index) => (
                                <StyledTableCell
                                    key={String(column.dataKey) + index}
                                    variant='head'
                                    align={column.numeric ? 'right' : 'left'}
                                    sx={{
                                        backgroundColor: 'background.paper',
                                        width: column.width,
                                        whiteSpace: 'nowrap',
                                    }}
                                >
                                    {column.renderHeaderCell ? column.renderHeaderCell(index) : column.label}
                                </StyledTableCell>
                            ))}
                        </StyledTableRow>
                    </TableHead>
                    <TableBody>
                        {isEmpty ? (
                            <StyledTableRow>
                                <StyledTableCell colSpan={columns.length}>Empty</StyledTableCell>
                            </StyledTableRow>
                        ) : loading ? (
                            <StyledTableRow>
                                <StyledTableCell colSpan={columns.length}>
                                    <Loader p={4} size={96} />
                                </StyledTableCell>
                            </StyledTableRow>
                        ) : (
                            data.map((row: any, rowIndex) => {
                                const status = boxStatuses[row.id];

                                return (
                                    <StyledTableRow
                                        key={row.id}
                                        sx={{
                                            background: !row.hasInvoice ? 'inherit' : status ? '#a3e635' : '#f87171',
                                            ...(onClickRow
                                                ? {
                                                      cursor: 'pointer',
                                                      '&:hover': {
                                                          backgroundColor: '#f1f1f1',
                                                      },
                                                  }
                                                : {}),
                                        }}
                                        onClick={() => onClickRow?.(row)}
                                    >
                                        {columns.map((column, index) => (
                                            <StyledTableCell
                                                key={String(column.dataKey) + index}
                                                align={column.numeric ? 'right' : 'left'}
                                                sx={{
                                                    ...column.getSxStyles?.(row),
                                                    width: column.width,
                                                }}
                                            >
                                                {column.renderCell ? column.renderCell(row, rowIndex) : row[column.dataKey as keyof Data]}
                                            </StyledTableCell>
                                        ))}
                                    </StyledTableRow>
                                );
                            })
                        )}
                    </TableBody>
                </StyledTable>
            </Scrollbar>
        </Box>
    );
};

export default MyTable;
