'use client';

import { useCallback, useMemo, useState, useEffect } from 'react';
import { Box, Dialog, 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 {
  INITIAL_DRIVER_ROADMAP_DATA,
} from '@/shared/types/roadMap';
import { type TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { TableType } from '@/shared/types/common';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import RoadmapTableRow from './invalid-roadmap-table-row';
import type { IDriver } from '@/shared/types/driver';
import type { IRoadmap, RoadMapPageFilterParams } from '@/shared/types/roadMap';

import { RoadMapStyledSelect, RoadMapStyledDatePicker, StyledMenuItem } from '@/shared/theme/css';
import { DEPARTEMENT_OPTIONS } from '@/shared/sections/establishment/attendance/utils/form-fields-attendance';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import type { Dayjs } from 'dayjs';
import { HEADER } from '@/layouts/config-layout';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faSquarePlus } from '@fortawesome/free-solid-svg-icons';
import ValidateRoadmapView from '../../../view/validate-roadMap-view';
import { paths } from '@/routes/paths';
import { useRouter } from '@/hooks/use-router';
import SendEmailDialog from '../old-roadmaps/contact-email-dialog';
import SendSmsDialog from '../old-roadmaps/contact-sms-dialog';
import ContactMethodDialog from '../old-roadmaps/contact-dialog';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

import { _drivers } from '@/shared/_mock/_drivers';
import NewRoadmapDialog from '../invalid-roadmap-dialog';

import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import { useRoadMapTable } from '../../hooks/use-invalid-roadmap-table';
import dayjs from 'dayjs';




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

type FilterKey = 'departement' | 'date';

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

export default function InValidRoadmapListView({ onIsListChange ,status }: RoadmapListViewProps) {
  const [filterValues, setFilterValues] = useState<Record<FilterKey, string>>({
    departement: '',
    date: '',
  });

  const [isContactDialogOpen, setContactDialogOpen] = useState(false);
  const [selectedRoadmap, setSelectedRoadmap] = useState<IRoadmap | null>(null);
  const [contactMethod, setContactMethod] = useState<'email' | 'sms' | 'internalChat' | null>(null);
  const [isNewRoadmapDialogOpen, setIsNewRoadmapDialogOpen] = useState(false);



  const [params, setParams] = useState<RoadMapPageFilterParams>({
    status:status,
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'desc'
  });
  
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCopy,
  } = useTabsManager<IRoadmap>(roadmapTabsConfig);
  const { validatedRoadMap, loading, error, getAllValidRoadMap } = useRoadMapStore();

  const { table, filteredData, filters, tableHead, notFound, handleFilterChange, handleStatusChange} =
    useRoadMapTable(validatedRoadMap || []);

  const activeTabData = useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);

  useEffect(() => {
      const newParams: RoadMapPageFilterParams = {
        status:status,
        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]);
  
  useEffect(() => {
    getAllValidRoadMap(params);
  }, [params]);
  const handleFilterValueChange = (key: FilterKey, value: string) => {
    setFilterValues((prev) => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleDatePickerChange = (date: Date | Dayjs | null) => {
  const dateString = date ? (dayjs(date).format('YYYY-MM-DD')) : '';
  handleFilterValueChange('date', dateString);
  
};
    const router = useRouter()
  const handleAddNewClick = () => {
    router.push( `${paths.dashboard.exploitation.chauffeur.feuilleRoute}/add-new-roadmap`);
  };
  const handleOldRoadMapsClick = () => {
    router.push( `${paths.dashboard.exploitation.chauffeur.feuilleRoute}/old-roadmaps`);
  };
  const handleContactClick = (roadmap: IRoadmap) => {
    setSelectedRoadmap(roadmap);
    setContactDialogOpen(true);
  };
  const handleMethodSelect = (method: 'email' | 'sms' | 'internalChat') => {
    setContactMethod(method);
    setContactDialogOpen(false);
  };

  const renderRow = useCallback(
    (row: IRoadmap) => (
      <RoadmapTableRow
        key={row.id}
        dense={table.dense}
        row={row}
        handleEdit={handleEdit}
        handleCopy={handleCopy}
        handleDetails={handleView}
        selected={table.selected.includes(row.id)}
        onSelectRow={() => table.onSelectRow(row.id)}
        columns={tableHead}
        onStatusChange={handleStatusChange}
        onClickOldRoadMaps={handleOldRoadMapsClick}
        onClickContact={handleContactClick}
      />
    ),
    [table, handleEdit, handleCopy, handleView, tableHead, handleStatusChange, handleOldRoadMapsClick]
  );

  const isList = activeTab === 'list';

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

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

  const handleNewRoadmap = (data: {
    driver: IDriver | null | IDriver[];
    startDate: Dayjs | Date | null;
  }) => {
    setIsNewRoadmapDialogOpen(false);
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <ContactMethodDialog
        open={isContactDialogOpen}
        onClose={() => setContactDialogOpen(false)}
        onSelect={handleMethodSelect}
      />

      <NewRoadmapDialog
        open={isNewRoadmapDialogOpen}
        onClose={() => setIsNewRoadmapDialogOpen(false)}
        onSend={handleNewRoadmap}
        drivers={_drivers}
      />

      <ConditionalComponent isValid={!!(selectedRoadmap && contactMethod === 'email')}>
          <SendEmailDialog
            open={contactMethod === 'email'}
            onClose={() => setContactMethod(null)}
            roadmap={selectedRoadmap!} 
          />
      </ConditionalComponent>

      <ConditionalComponent isValid={!!(selectedRoadmap && contactMethod === 'sms')}>
        <SendSmsDialog
          open={contactMethod === 'sms'}
            onClose={() => setContactMethod(null)}
            roadmap={selectedRoadmap!}
          />
      </ConditionalComponent>

      <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={() => setIsNewRoadmapDialogOpen(true)}
            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}
        />

        {isList ? (
          <>
            <Stack
              flexGrow={0}
              direction="row"
              justifyContent="flex-start"
              spacing={{ xs: 0.5, sm: 1 }}
              sx={{ my: 2 }}
            >
              <RoadMapStyledSelect
                name="departement"
                onChange={(e) => handleFilterValueChange('departement', e.target.value as string)}
                value={filterValues.departement}
                displayEmpty
                renderValue={(selected) => {
                  if (selected === '') {
                    return <Typography sx={{ color: '#A2A6AB' }}>{'Département'}</Typography>;
                  }
                  return (
                    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>
            <TableManager
              filteredData={filteredData}
              table={table}
              tableHead={tableHead}
              notFound={notFound}
              filters={filters}
              onFilterChange={handleFilterChange}
              renderRow={renderRow}
            />
          </>
        ) : (
       <ValidateRoadmapView></ValidateRoadmapView>

        )}
      </Box>
    </LocalizationProvider>
  );
}
