'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { Box, Stack, Typography } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { type TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import TableManager from '@/shared/components/table/table-manager';
import type { IValidRoadmap, ValidRoadmapFilterParams } from '@/shared/types/driver';
import { RoadMapStyledDatePicker, RoadMapStyledSelect, StyledMenuItem } from '@/shared/theme/css';
import { DEPARTEMENT_OPTIONS } from '@/shared/sections/establishment/attendance/utils/form-fields-attendance';
import ValidRoadmapTableRow from './valid-roadmap-table-row';
import {
  _validRoadmapData,
  DEFAULT_VALID_ROADMAP_TABLE_HEAD,
  INITIAL_VALID_ROADMAP,
} from '@/shared/_mock/_validRoadmap';
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from '@/shared/types/common';
import { Dayjs } from 'dayjs';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import { useRouter } from '@/hooks/use-router';
import { paths } from '@/routes/paths';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faSquarePlus } from '@fortawesome/free-solid-svg-icons';
import { HEADER } from '@/layouts/config-layout';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import { de } from 'date-fns/locale';

const roadmapConfig: TableConfig<IValidRoadmap> = {
  initialData: _validRoadmapData,
  defaultTableHead: DEFAULT_VALID_ROADMAP_TABLE_HEAD,
};

const roadmapTabsConfig: TabConfig<IValidRoadmap> = {
  type: TableType.DriverRoadmap,
  listTitle: 'Liste feuilles de route',
  newItemTitle: 'Validation des feuilles de route',
  initialData: INITIAL_VALID_ROADMAP,
  getItemCode: (roadmap) => roadmap.id,
};

type FilterKey = 'departement' | 'date';

interface RoadmapListViewProps {
  onIsListChange?: (isList: boolean) => void;
}

export default function ValidRoadmapListView({ onIsListChange }: RoadmapListViewProps) {
  const { dealvalidatedRoadMap, getAllDealValidRoadMap, loading, error } = useRoadMapStore();
  const [filterValues, setFilterValues] = useState<Record<FilterKey, string>>({
    departement: '',
    date: '',
  });

  const router = useRouter();

  const { tabs, activeTab, handleTabChange, handleTabClose } =
    useTabsManager<IValidRoadmap>(roadmapTabsConfig);

  const isList = activeTab === 'list';

  useEffect(() => {
    if (onIsListChange) {
      onIsListChange(isList);
    }
  }, [isList, onIsListChange]);

  const { table, filteredData, filters, tableHead, notFound, handleFilterChange, dataToExport } =
    useTableManager<IValidRoadmap>(roadmapConfig);

  useEffect(() => {
    const newParams: ValidRoadmapFilterParams = {
      page: table.page,
      size: table.rowsPerPage,
      sortBy: table.orderBy,
      sortDirection: table.order.toLowerCase() as 'asc' | 'desc',
    };

    const filterParams: Record<string, string> = {};
    Object.entries(filters).forEach(([key, { value }]) => {
      if (value) {
        filterParams[key] = value;
      }
    });

    setParams({ ...newParams, ...filterParams });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

  const [params, setParams] = useState<ValidRoadmapFilterParams>({
    page: 0,
    size: 5,
    sortBy: 'id',
    sortDirection: 'desc',
  });

  useEffect(() => {
    getAllDealValidRoadMap(params);
  }, [params]);

  const handleFilterValueChange = (key: FilterKey, value: string) => {
    setFilterValues((prev) => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleDatePickerChange = (date: Date | Dayjs | null) => {
    const dateString = date ? date.toISOString().split('T')[0] : '';
    handleFilterValueChange('date', dateString);
  };

  const handleOldRoadMapsClick = (roadmap: IValidRoadmap) => {
    router.push(
      `${paths.dashboard.exploitation.chauffeur.feuilleRoute}/old-roadmaps/${roadmap.driverId}`
    );
  };

  const handleAddNewClick = () => {
    router.push(`${paths.dashboard.exploitation.chauffeur.feuilleRoute}/add-new-roadmap`);
  };

  const renderRow = useCallback(
    (row: IValidRoadmap) => (
      <ValidRoadmapTableRow
        key={row.id}
        dense={table.dense}
        row={row}
        selected={table.selected.includes(row.id)}
        onSelectRow={() => table.onSelectRow(row.id)}
        columns={tableHead}
        onClickOldRoadMaps={handleOldRoadMapsClick}
      />
    ),
    [table, tableHead]
  );

  const datePickerValue = filterValues.date ? new Date(filterValues.date) : null;

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          height: isList ? '650px' : `calc(100vh - ${HEADER.H_DESKTOP + 143}px)`,
        }}
      >
        <Stack flexGrow={0} direction="row" justifyContent="flex-end">
          <AddButton
            onClick={handleAddNewClick}
            variant="contained"
            endIcon={<FontAwesome icon={faSquarePlus} width={18} />}
          >
            {'Nouvelle feuille de route'}
          </AddButton>
        </Stack>

        <TabsCustom
          type={TableType.DriverRoadmap}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />

        <ConditionalComponent isValid={isList}>
          <>
            <Stack
              direction="row"
              justifyContent="space-between"
              alignItems="center"
              spacing={1}
              sx={{ my: 2 }}
            >
              <Stack direction="row" spacing={1}>
                <RoadMapStyledSelect
                  name="departement"
                  onChange={(e) => handleFilterValueChange('departement', e.target.value as string)}
                  value={filterValues.departement}
                  displayEmpty
                  renderValue={(selected) =>
                    selected === '' ? (
                      <Typography sx={{ color: '#A2A6AB' }}>{'Département'}</Typography>
                    ) : (
                      DEPARTEMENT_OPTIONS.find((option) => option.value === selected)?.label || ''
                    )
                  }
                >
                  {DEPARTEMENT_OPTIONS.map((option) => (
                    <StyledMenuItem key={option.value} value={option.value}>
                      {option.label}
                    </StyledMenuItem>
                  ))}
                </RoadMapStyledSelect>

                <RoadMapStyledDatePicker
                  value={datePickerValue}
                  onChange={handleDatePickerChange}
                  views={['year', 'month', 'day']}
                  slots={{ openPickerIcon: CustomDateIcon }}
                  openTo="year"
                  slotProps={{
                    textField: {
                      placeholder: 'Filtrer par date',
                      InputLabelProps: {
                        shrink: true,
                      },
                    },
                  }}
                />
              </Stack>

              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <ExportButton
                  isTableExport
                  tooltipTitle="Exporter"
                  type={TableType.DriverRoadmap}
                  filteredData={dataToExport}
                  tableHead={tableHead}
                />
              </Box>
            </Stack>

            <TableManager
              filteredData={dealvalidatedRoadMap}
              table={table}
              tableHead={tableHead}
              notFound={notFound}
              filters={filters}
              onFilterChange={handleFilterChange}
              renderRow={renderRow}
              loading={loading}
              
            />
          </>
        </ConditionalComponent>
      </Box>
    </LocalizationProvider>
  );
}
