'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { Box, IconButton, 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,
  WhiteIconButtonStyle,
} 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 { faRotate, 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, fr } 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 = 'startDate' | 'endDate';

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

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

  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,
      page: Object.keys(filterParams).length > 0 ? 0 : newParams.page,
      ...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,
    }));
  };

  useEffect(() => {
    const { startDate, endDate } = filterValues;

    if (startDate && endDate && new Date(endDate) >= new Date(startDate)) {
      setParams((prev) => ({
        ...prev,
        page: 0,
        startDate,
        endDate,
      }));
    }
  }, [filterValues.startDate, filterValues.endDate]);

  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]
  );

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <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: 3 }}
            >
              <Stack direction="row" spacing={1}>
                <RoadMapStyledDatePicker
                  value={filterValues.startDate ? new Date(filterValues.startDate) : null}
                  onChange={(date) => {
                    const dateString = date ? date.toISOString().split('T')[0] : '';
                    handleFilterValueChange('startDate', dateString);
                  }}
                  views={['year', 'month', 'day']}
                  slots={{ openPickerIcon: CustomDateIcon }}
                  openTo="year"
                  slotProps={{
                    textField: {
                      placeholder: 'Date début',
                      InputLabelProps: { shrink: true },
                    },
                  }}
                />

                <RoadMapStyledDatePicker
                  value={filterValues.endDate ? new Date(filterValues.endDate) : null}
                  onChange={(date) => {
                    const dateString = date ? date.toISOString().split('T')[0] : '';
                    handleFilterValueChange('endDate', dateString);
                  }}
                  views={['year', 'month', 'day']}
                  slots={{ openPickerIcon: CustomDateIcon }}
                  openTo="year"
                  slotProps={{
                    textField: {
                      placeholder: 'Date fin',
                      InputLabelProps: { shrink: true },
                    },
                  }}
                />

                <IconButton
                  onClick={() => {
                    setParams((prev) => ({
                      ...prev,
                      page: 0,
                      startDate: null,
                      endDate: null,
                    }));
                    setFilterValues({
                      ...filterValues,
                      startDate: '',
                      endDate: '',
                    });
                  }}
                  sx={WhiteIconButtonStyle}
                >
                  <FontAwesome icon={faRotate} width={18} style={{ fontSize: 18 }} />
                </IconButton>
              </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}
              count={totalElements}
            />
          </>
        </ConditionalComponent>
      </Box>
    </LocalizationProvider>
  );
}
