'use client';

import React, { useCallback, useState } from 'react';
import { Card, Container, Tab, Tabs, TablePagination, Box, styled, Paper, ListItem, List, ListItemIcon, ListItemText, Button } from '@mui/material';
import { alpha, useTheme } from '@mui/material/styles';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { useSettingsContext } from '@/shared/components/settings';
import InvoiceListHeader from '../invoice-list-header';
import InvoiceListFilters from '../invoice-list-filters';
import InvoiceListTable from '../invoice-list-table';
import InvoiceListActions from '../invoice-list-actions';
import { useInvoiceList } from '@/hooks/use-invoice-list';
import { getInvoiceLength } from '@/utils/invoice-filter';
import Label from '@/components/label';
import theme from '@/shared/theme';
import InvoiceTableFiltersResult from '../invoice-table-filters-result';
import Iconify from '@/shared/components/iconify';
import { paths } from '@/routes/paths';
import { useRouter } from 'next/navigation';
import InvoiceLayout from './invoice-layout';
import { RouterLink } from '@/routes';


export default function InvoiceListView() {
  const settings = useSettingsContext();
  const [selectedPath, setSelectedPath] = useState(paths.dashboard.invoice.root); // Chemin par défaut
  const theme = useTheme();
  const router = useRouter();

  const handleNavigation = (path: string) => {
    setSelectedPath(path);
    router.push(path);
  };


  const {
    tableData,
    filters,
    dataFiltered,
    dataInPage,
    handleFilters,
    handleDeleteRow,
    handleDeleteRows,
    handleEditRow,
    handleViewRow,
    table,
    confirm,
    view,
    paymentModeOptions,
    dateError,
    page,
    setPage,
    rowsPerPage,
    setRowsPerPage,
  } = useInvoiceList();

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

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

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleResetFilters = useCallback(() => {
    setPage(0);
    handleFilters('status', 'all');
    handleFilters('paymentMode', []);
    handleFilters('startDate', null);
    handleFilters('endDate', null);
  }, [handleFilters]);
  const hasFilters = filters.status !== 'all' ||
    !!filters.paymentMode.length ||
    (!!filters.startDate && !!filters.endDate);
  return (
    <InvoiceLayout>
      <LocalizationProvider dateAdapter={AdapterDayjs}>

        <Container maxWidth={settings.themeStretch ? false : 'lg'}>
          {/* <InvoiceListHeader /> */}
          <Card>
            <Tabs
              value={filters.status}
              onChange={handleFilterStatus}
              sx={{
                px: 2.5,
                boxShadow: `inset 0 -2px 0 0 ${alpha(theme.palette.grey[500], 0.08)}`,
              }}
            >
              {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>
                  }
                />
              ))}
              <Box sx={{ width: '100%', display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                <Button
                  component={RouterLink}
                  sx={{
                    backgroundColor: '#144dd5',
                    '&:hover': {
                      backgroundColor: '#144dd5',
                    },
                    textTransform: 'none',
                    height: 40,
                    px: 2,
                  }}
                  href={paths.dashboard.invoice.new}
                  variant="contained"
                  startIcon={<Iconify icon="mingcute:add-line" />}
                >
                  New Invoice
                </Button>
              </Box>
            </Tabs>
          </Card>

          <InvoiceListFilters
            onResetFilters={handleResetFilters}
            filters={filters}
            onFilters={handleFilters}
            dateError={dateError}
            paymentModeOptions={paymentModeOptions}
          />
          {hasFilters ? (
            <InvoiceTableFiltersResult
              filters={filters}
              onFilters={handleFilters}
              onResetFilters={handleResetFilters}
              results={dataFiltered.length}
              sx={{ mb: 2.5 }}
            />
          ) : (
            <Box sx={{ height: 40 }} />
          )}
          <InvoiceListTable
            dataFiltered={dataFiltered}
            dataInPage={dataInPage}
            table={table}
            onDeleteRow={handleDeleteRow}
            onEditRow={handleEditRow}
            onViewRow={handleViewRow}
          />
          <TablePagination
            component="div"
            count={dataFiltered.length}
            page={page}
            onPageChange={handleChangePage}
            rowsPerPage={rowsPerPage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
          <InvoiceListActions
            selected={table.selected}
            onDeleteRows={handleDeleteRows}
            tableData={tableData}
            view={view}
            confirm={confirm}
          />

        </Container>

      </LocalizationProvider>
    </InvoiceLayout>

  );
}