'use client';

import sumBy from 'lodash/sumBy';
import { useState, useCallback } from 'react';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Container from '@mui/material/Container';
import { useTheme } from '@mui/material/styles';
import { paths } from '@/routes/paths';
import { useRouter } from '@/hooks';
import RouterLink from '@/routes/router-link';
import { useBoolean } from '@/hooks';
import { isAfter, isBetween } from '@/utils/format-time';
import { _invoices, INVOICE_PAYMENT_MODE_OPTIONS } from '@/shared/_mock';
import Label from '@/shared/components/label';
import Iconify from '@/shared/components/iconify';
import { useSnackbar } from '@/shared/components/snackbar';
import { useSettingsContext } from '@/shared/components/settings';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import CustomBreadcrumbs from '@/shared/components/custom-breadcrumbs';
import { useTable, getComparator } from '@/shared/components/table';
import { IInvoice, IInvoiceTableFilters, IInvoiceTableFilterValue } from '@/shared/types/invoice';
import InvoiceItemGridView from '../invoice-item-grid-view';
import InvoiceTableToolbar from '../invoice-table-toolbar';
import InvoiceTableFiltersResult from '../invoice-table-filters-result';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import Box from '@mui/material/Box';
import Pagination, { paginationClasses } from '@mui/material/Pagination';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import InvoiceLayout from './invoice-layout';


// ----------------------------------------------------------------------

const defaultFilters: IInvoiceTableFilters = {
  name: '',
  paymentMode:[],
  status: 'all',
  startDate: null,
  endDate: null,
};

// ----------------------------------------------------------------------

export default function InvoiceGridView() {

  const invoice = _invoices;

  const confirm = useBoolean();


  const [view, setView] = useState('grid');

  const { enqueueSnackbar } = useSnackbar();

  const settings = useSettingsContext();

  const router = useRouter();

  const table = useTable({ defaultOrderBy: 'createDate' });

  const [tableData, setTableData] = useState<IInvoice[]>(_invoices);

  const [filters, setFilters] = useState(defaultFilters);

  const dateError = isAfter(filters.startDate, filters.endDate);
  //---------------------------------------------------


  const handleView = useCallback(
    (id: string) => {
      router.push(paths.dashboard.invoice.details(id));
    },
    [router]
  );

  const handleEdit = useCallback(
    (id: string) => {
      router.push(paths.dashboard.invoice.edit(id));
    },
    [router]
  );

  const handleDelete = useCallback((id: string) => {
    console.info('DELETE', id);
  }, []);

  //---------------------------------------------------

  const handleChangeView = useCallback(
    (event: React.MouseEvent<HTMLElement>, newView: string | null) => {
      if (newView !== null) {
        setView(newView);
      }
    },
    []
  );

  const dataFiltered = applyFilter({
    inputData: tableData,
    comparator: getComparator(table.order, table.orderBy),
    filters,
    dateError,
  });

  const dataInPage = dataFiltered.slice(
    table.page * table.rowsPerPage,
    table.page * table.rowsPerPage + table.rowsPerPage
  );

  const denseHeight = table.dense ? 56 : 56 + 20;

  const canReset =
    !!filters.name ||
    !!filters.paymentMode.length ||
    filters.status !== 'all' ||
    (!!filters.startDate && !!filters.endDate);

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

  const getInvoiceLength = (status: string) =>
    tableData.filter((item) => item.status === status).length;

  const TABS = [
    { value: 'all', label: 'All', color: 'default', count: tableData.length },
    {
      value: 'paid',
      label: 'Paid',
      color: 'success',
      count: getInvoiceLength('paid'),
    },
    {
      value: 'pending',
      label: 'Pending',
      color: 'warning',
      count: getInvoiceLength('pending'),
    },
    {
      value: 'overdue',
      label: 'Overdue',
      color: 'error',
      count: getInvoiceLength('overdue'),
    },
    {
      value: 'draft',
      label: 'Draft',
      color: 'info',
      count: getInvoiceLength('draft'),
    },
    {
      value: 'deleted',
      label: 'Deleted',
      color: 'default',
      count: getInvoiceLength('deleted'),
    },
  ] as const;

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

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

  const handleDeleteRow = useCallback(
    (id: string) => {
      confirm.onTrue();
      const deleteRow = tableData.filter((row) => row.id !== id);

      //enqueueSnackbar('Delete success!');

      setTableData(deleteRow);

      table.onUpdatePageDeleteRow(dataInPage.length);
    },
    [dataInPage.length, enqueueSnackbar, table, tableData]
  );

  const handleDeleteRows = useCallback(() => {
    const deleteRows = tableData.filter((row) => !table.selected.includes(row.id));

    enqueueSnackbar('Delete success!');

    setTableData(deleteRows);

    table.onUpdatePageDeleteRows({
      totalRowsInPage: dataInPage.length,
      totalRowsFiltered: dataFiltered.length,
    });
  }, [dataFiltered.length, dataInPage.length, enqueueSnackbar, table, tableData]);

  const handleEditRow = useCallback(
    (id: string) => {
      router.push(paths.dashboard.invoice.edit(id));
    },
    [router]
  );

  const handleViewRow = useCallback(
    (id: string) => {
      router.push(paths.dashboard.invoice.details(id));
    },
    [router]
  );

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

  return (
    <InvoiceLayout>
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth={settings.themeStretch ? false : 'lg'}>
        <CustomBreadcrumbs
          heading="Grid"
          links={[
            {
              name: 'Dashboard',
              href: paths.dashboard.root,
            },
            {
              name: 'Invoice',
              href: paths.dashboard.invoice.root,
            },
            {
              name: 'Grid',
            },
          ]}
          action={
            <Button
              component={RouterLink}
              href={paths.dashboard.invoice.new}
              variant="contained"
              sx={{
                backgroundColor: '#144dd5',
                '&:hover': {
                  backgroundColor: '#144dd5',
                },
            
                textTransform: 'none',
                px: 2,
                marginLeft: 2,
              }}
              startIcon={<Iconify icon="mingcute:add-line" />}
            >
              New Invoice
            </Button>
          }
          sx={{
            mb: { xs: 3, md: 5 },
          }}
        />

        <Stack
          spacing={1}
          direction={{ xs: 'column', md: 'row' }}
          alignItems={{ xs: 'flex-end', md: 'center' }}
          marginBottom="20px"
          sx={{ width: 1 }}
        >
          <Stack spacing={1} direction="row" alignItems="center" justifyContent="flex-end" flexGrow={1}>
            <ToggleButtonGroup size="small" value={view} exclusive onChange={handleChangeView}>
              <ToggleButton value="list">
                <a href={paths.dashboard.invoice.root}>
                  <Iconify icon="solar:list-bold" />
                </a>
              </ToggleButton>
              <ToggleButton value="grid">
                <a href={paths.dashboard.invoice.grid}>
                  <Iconify icon="mingcute:dot-grid-fill" />
                </a>
              </ToggleButton>
              <ToggleButton value="analytic">
                <a href={paths.dashboard.invoice.analytics}>
                  <Iconify icon="carbon:analytics" />
                </a>
              </ToggleButton>
            </ToggleButtonGroup>
          </Stack>
        </Stack>
        <Card>
          <Tabs
            value={filters.status}
            onChange={handleFilterStatus}
            sx={{
              px: 2.5,
              boxShadow: `inset 0 -2px 0 0 `,
            }}
          >
            {TABS.map((tab) => (
              <Tab
                key={tab.value}
                value={tab.value}
                label={tab.label}
                iconPosition="end"
                icon={
                  <Label
                    variant={
                      ((tab.value === 'all' || tab.value === filters.status) && 'filled') || 'soft'
                    }
                    color={tab.color}
                  >
                    {tab.count}
                  </Label>
                }
              />
            ))}
          </Tabs>

          <InvoiceTableToolbar
            filters={filters}
            onFilters={handleFilters}
            //
            dateError={dateError}
            paiementOptions={INVOICE_PAYMENT_MODE_OPTIONS.map((option) => option.name)}
          />

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

        <Stack

          alignItems={{ xs: 'flex-end', md: 'center' }}
          marginBottom="20px"
          marginTop="30px"
          sx={{ width: 1 }}
        >
          {invoice && (
            <Box
              gap={3}
              display="grid"
              gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                sm: 'repeat(2, 1fr)',
                md: 'repeat(3, 1fr)'
              }}
              
            >
              {invoice.map((inv) => (
                <InvoiceItemGridView
                  key={inv.id}
                  invoice={inv}
                  onView={() => handleView(inv.id)}
                  onEdit={() => handleEdit(inv.id)}
                  onDelete={() => handleDeleteRow(inv.id)}
                />
              ))}
            </Box>
          )}

          {invoice && invoice.length > 8 && (
            <Pagination
              count={8}
              sx={{
                mt: 8,
                [`& .${paginationClasses.ul}`]: {
                  justifyContent: 'center',
                },
              }}
            />
          )}
        </Stack>

        <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>
          }
        />

      </Container>
    </LocalizationProvider>
    </InvoiceLayout>
  );
}

// ----------------------------------------------------------------------

function applyFilter({
  inputData,
  comparator,
  filters,
  dateError,
}: {
  inputData: IInvoice[];
  comparator: (a: any, b: any) => number;
  filters: IInvoiceTableFilters;
  dateError: boolean;
}) {
  const { name, status, paymentMode, startDate, endDate } = 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 (name) {
    inputData = inputData.filter(
      (invoice) =>
        invoice.invoiceNumber.toLowerCase().indexOf(name.toLowerCase()) !== -1 ||
        invoice.invoiceClient?.company?.toLowerCase().indexOf(name.toLowerCase()) !== -1
    );
  }

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

  if (paymentMode.length) {
  }

  if (!dateError) {
    console.log("startDate ------>" + startDate);
    console.log(startDate instanceof Date);
    console.log("endDate ------>" + endDate);
    console.log(endDate instanceof Date);
    if (startDate && endDate) {
      inputData = inputData.filter((invoice) => isBetween(invoice.createDate, startDate, endDate));
    }
  }

  return inputData;
}
