'use client'

import { useCallback, useEffect, useState } from "react";
import { Button, Card, IconButton, Stack, Tab, Table, TableBody, TableContainer, Tabs, Tooltip, alpha } from "@mui/material";
import { useSettingsContext } from "@/shared/components/settings";
import { ITransfer, ITransferTableFilterValue, ITransferTableFilters } from "@/shared/types/transfer";
import useTable from "@/shared/components/table/use-table";
import { TableEmptyRows, TableHeadCustom, TableNoData, TablePaginationCustom, TableSelectedAction, emptyRows, getComparator } from "@/shared/components/table";
import { useBoolean } from "@/hooks";
import Scrollbar from "@/components/scrollbar";
import { useSnackbar } from "@/components/snackbar";
import { ConfirmDialog } from "@/components/custom-dialog";
import TransferTableToolbar from "./transfer-table-toolbar";
import TransferTableRow from "./transfer-table-row";
import TransferTableFiltresResult from "./transfer-table-filter";
import Label from "@/components/label";
import Iconify from "@/shared/components/iconify";
import { useTransfers } from "@/hooks/use-list-transfer";
import { LoadingScreen } from "@/shared/components/loading-screen";
import { transferApi } from "@/shared/api/transfer-file";

const defaultFilters: ITransferTableFilters = {
    title: '',
    status: 'all'
};

const STATUS_OPTIONS = [
    { 
        value: 'all', 
        label: 'All', 
        color: 'default', 
        bgColor: (theme:any) => alpha(theme.palette.grey[500], 0.08),
    },
    { 
        value: 'expired', 
        label: 'Expired', 
        color: 'error', 
        bgColor: (theme:any) => alpha(theme.palette.error.main, 0.08),
    },
    { 
        value: 'valid', 
        label: 'Valid', 
        color: 'success', 
        bgColor: (theme: { palette: { success: { main: string; }; }; }) => alpha(theme.palette.success.main, 0.08),
        textColor: (theme: { palette: { success: { main: any; }; }; }) => theme.palette.success.main
    }
];

const TABLE_HEAD = [
    { id: 'title', label: 'Title', align: 'left', width: '40%' },
    { id: 'expiryDate', label: 'Expiry Date', align: 'left', width: '30%' },
    { id: 'status', label: 'Status', align: 'left', width: '20%' },
    { id: 'actions', width: '10%' }
];

export default function TransferListView() {
    const settings = useSettingsContext();
    const table = useTable({ defaultOrderBy: 'expiryDate' });
    const confirm = useBoolean();
    const { enqueueSnackbar } = useSnackbar();
    const denseHeight = table.dense ? 56 : 76;

    const { transfers, loading, error, getTransfers} = useTransfers();
    const [filters, setFilters] = useState(defaultFilters);
    const dataFiltered = applyFilter({
      inputData: transfers,
      comparator: getComparator(table.order, table.orderBy),
      filters,
  });
  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
);
    useEffect(() => {
        getTransfers();
    }, [getTransfers]);

    const handleDeleteRow = useCallback(
        async (id: string) => {
            try {
                await transferApi.deleteTransfer(id);
                getTransfers();
                enqueueSnackbar('Delete success!');
                table.onUpdatePageDeleteRow(dataInPage.length);
            } catch (error) {
                console.error('Error deleting transfer:', error);
                enqueueSnackbar('Error deleting transfer', { variant: 'error' });
            }
        },
        [dataInPage.length, enqueueSnackbar, table, getTransfers]
    );

    const handleDeleteRows = useCallback(async () => {
        try {
            await Promise.all(table.selected.map((id) => transferApi.deleteTransfer(id)));
            getTransfers();
            enqueueSnackbar('Transfers deleted successfully!');
            table.onUpdatePageDeleteRows({
                totalRowsInPage: dataInPage.length,
                totalRowsFiltered: dataFiltered.length,
            });
            table.onSelectAllRows(false, []);
        } catch (error) {
            console.error('Error deleting transfers:', error);
            enqueueSnackbar('Error deleting transfers', { variant: 'error' });
        }
    }, [table, dataInPage.length, dataFiltered.length, enqueueSnackbar, getTransfers]);

    const getStatusCount = (status: string) => {
        if (status === 'all') return transfers.length;
        return transfers.filter((transfer) => transfer.status === status).length;
    };

   
    const notFound = (!dataFiltered.length && !!filters.title) || !dataFiltered.length;

  

    const handleFilters = useCallback(
        (name: string, value: ITransferTableFilterValue) => {
            table.onResetPage();
            setFilters((prevState) => ({
                ...prevState,
                [name]: value,
            }));
        },
        [table]
    );

    const handleResetFilters = useCallback(() => {
        setFilters(defaultFilters);
    }, []);

    const handleFilterStatus = useCallback(
        (event: React.SyntheticEvent, newValue: string) => {
            handleFilters('status', newValue);
        },
        [handleFilters]
    );

    if (loading) {
        return <LoadingScreen />;
    }

    if (error) {
        return <div>Error: {error}</div>;
    }

    return (
        <>
            <Card>
                <Tabs
                    value={filters.status}
                    onChange={handleFilterStatus}
                    sx={{
                        px: 2.5,
                        '& .MuiTabs-flexContainer': {
                            gap: 1,
                        },
                    }}
                >
                    {STATUS_OPTIONS.map((tab) => (
                        <Tab
                            key={tab.value}
                            value={tab.value}
                            label={
                                <Stack direction="row" spacing={1} alignItems="center">
                                    {tab.label}
                                    <Label
                                        sx={{
                                            height: 22,
                                            minWidth: 22,
                                            borderRadius: '6px',
                                            bgcolor: typeof tab.bgColor === 'function' ? tab.bgColor : tab.bgColor,
                                            color: typeof tab.textColor === 'function' ? tab.textColor : tab.textColor,
                                            fontWeight: 'normal',
                                            '& .MuiChip-label': {
                                                px: 0.75,
                                                fontSize: 12
                                            }
                                        }}
                                    >
                                        {getStatusCount(tab.value)}
                                    </Label>
                                </Stack>
                            }
                            sx={{
                                '&.Mui-selected': {
                                    fontWeight: 'bold',
                                },
                            }}
                        />
                    ))}
                </Tabs>

                <TransferTableToolbar
                    filters={filters}
                    onFilters={handleFilters}
                />

                {!!filters.title && (
                    <TransferTableFiltresResult
                        filters={filters}
                        onFilters={handleFilters}
                        onResetFilters={handleResetFilters}
                        results={dataFiltered.length}
                        sx={{ p: 2.5, pt: 0 }}
                    />
                )}

                <TableContainer sx={{ position: 'relative', overflow: 'unset' }}>
                    <TableSelectedAction
                        dense={table.dense}
                        numSelected={table.selected.length}
                        rowCount={dataFiltered.length}
                        onSelectAllRows={(checked) =>
                            table.onSelectAllRows(
                                checked,
                                dataFiltered.map((row) => row.id)
                            )
                        }
                        action={
                            <Stack direction="row">
                                <Tooltip title="Delete">
                                    <IconButton color="primary" onClick={confirm.onTrue}>
                                        <Iconify icon="solar:trash-bin-trash-bold" />
                                    </IconButton>
                                </Tooltip>
                            </Stack>
                        }
                    />

                    <Scrollbar>
                        <Table size={table.dense ? 'small' : 'medium'} sx={{ minWidth: 800 }}>
                            <TableHeadCustom
                                order={table.order}
                                orderBy={table.orderBy}
                                headLabel={TABLE_HEAD}
                                rowCount={dataFiltered.length}
                                numSelected={table.selected.length}
                                onSort={table.onSort}
                                onSelectAllRows={(checked) =>
                                    table.onSelectAllRows(
                                        checked,
                                        dataFiltered.map((row) => row.id)
                                    )
                                }
                            />

                            <TableBody>
                                {dataInPage.map((row) => (
                                    <TransferTableRow
                                        key={row.id}
                                        row={row}
                                        selected={table.selected.includes(row.id)}
                                        onSelectRow={() => table.onSelectRow(row.id)}
                                        onDeleteRow={() => handleDeleteRow(row.id)}
                                       
                                    />
                                ))}

                                <TableEmptyRows
                                    height={denseHeight}
                                    emptyRows={emptyRows(table.page, table.rowsPerPage, dataFiltered.length)}
                                />

                                <TableNoData notFound={notFound} />
                            </TableBody>
                        </Table>
                    </Scrollbar>
                </TableContainer>

                <TablePaginationCustom
                    count={dataFiltered.length}
                    page={table.page}
                    rowsPerPage={table.rowsPerPage}
                    onPageChange={table.onChangePage}
                    onRowsPerPageChange={table.onChangeRowsPerPage}
                    dense={table.dense}
                    onChangeDense={table.onChangeDense}
                />
            </Card>

            <ConfirmDialog
                open={confirm.value}
                onClose={confirm.onFalse}
                title="Delete"
                content={
                    <>
                        Are you sure want to delete <strong> {table.selected.length} </strong> items?
                    </>
                }
                action={
                    <Button
                        variant="contained"
                        color="error"
                        onClick={() => {
                            handleDeleteRows();
                            confirm.onFalse();
                        }}
                    >
                        Delete
                    </Button>
                }
            />
        </>
    );
}

function applyFilter({
    inputData,
    comparator,
    filters,
}: {
    inputData: ITransfer[];
    comparator: (a: any, b: any) => number;
    filters: ITransferTableFilters;
}) {
    const { title, status } = filters;

    const stabilizedThis = inputData.map((el, index) => [el, index] as const);

    stabilizedThis.sort((a, b) => {
        const order = comparator(a[0], b[0]);
        if (order !== 0) return order;
        return a[1] - b[1];
    });

    inputData = stabilizedThis.map((el) => el[0]);

    if (title) {
        inputData = inputData.filter(
            (transfer) => transfer.title.toLowerCase().indexOf(title.toLowerCase()) !== -1
        );
    }

    if (status !== 'all') {
        inputData = inputData.filter((transfer) => transfer.status === status);
    }

    return inputData;
}