'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, type SxProps, Table, TableBody, TableCell, TableHead, TableRow, type 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>>({});

    // Enhanced sorting: completed boxes (green) go to the bottom
    const sortedData = React.useMemo(() => {
        return [...data].sort((a: any, b: any) => {
            const aPrint = a.print ? 1 : 0;
            const bPrint = b.print ? 1 : 0;

            if (aPrint !== bPrint) {
                return aPrint - bPrint; // false (0) avval, true (1) keyin
            }

            const aStatus = boxStatuses[a.id] ? 1 : 0;
            const bStatus = boxStatuses[b.id] ? 1 : 0;

            if (aStatus !== bStatus) {
                return aStatus - bStatus;
            }

            return Number(a.id) - Number(b.id); // fallback sort
        });
    }, [data, boxStatuses]);

    React.useEffect(() => {
        const fetchBoxStatuses = async () => {
            if (!data.length || loading) return;

            const statuses: Record<string, boolean> = {};

            try {
                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 }
                            );

                            // Box is complete (green) when all items are accepted
                            statuses[row.id] = total.totalAmount === total.totalAccepted && total.totalAmount > 0;
                        } catch (error) {
                            console.error(`Error fetching box status for ${row.id}:`, error);
                            statuses[row.id] = false;
                        }
                    })
                );

                setBoxStatuses(statuses);
            } catch (error) {
                console.error('Error fetching box statuses:', error);
            }
        };

        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>
                        ) : (
                            sortedData.map((row: any, rowIndex) => {
                                const isCompleted = boxStatuses[row.id];
                                console.log(row, 'rows');

                                return (
                                    <StyledTableRow
                                        key={row.id}
                                        sx={{
                                            background: row.print
                                                ? '#dbeafe' // ko‘k rang (bg-blue-100)
                                                : !row.hasInvoice
                                                  ? 'inherit'
                                                  : isCompleted
                                                    ? '#dcfce7' // yashil (bg-green-100)
                                                    : '#fef2f2', // qizil (bg-red-100)
                                            borderLeft: !row.hasInvoice
                                                ? 'inherit'
                                                : row.print
                                                  ? '4px solid #3b82f6' // ko‘k chegara (border-blue-500)
                                                  : isCompleted
                                                    ? '4px solid #22c55e' // yashil chegara
                                                    : '4px solid #ef4444', // qizil chegara
                                            ...(onClickRow && !row.hasInvoice
                                                ? {
                                                      cursor: 'pointer',
                                                      '&:hover': {
                                                          backgroundColor: row.print
                                                              ? '#bfdbfe' // hover ko‘k (bg-blue-200)
                                                              : isCompleted
                                                                ? '#bbf7d0' // hover yashil (bg-green-200)
                                                                : '#fee2e2', // hover qizil (bg-red-200)
                                                      },
                                                  }
                                                : {}),
                                        }}
                                        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;
