'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 { IActiveDriver, IDriver } from '@/shared/types/driver';
import type { IRoadmap, RoadMapPageFilterParams, ValidatedRoadMapArgs } 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, { ValidateRoadmapViewProps } 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 fr from 'date-fns/locale/fr';

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,
};

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

export default function InValidRoadmapListView({ onIsListChange, status }: RoadmapListViewProps) {
  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, totalElements, 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,
      page: Object.keys(filterParams).length > 0 ? 0 : newParams.page,
      ...filterParams,
    });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

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

  const router = useRouter();
  const handleAddNewClick = () => {
    router.push(`${paths.dashboard.exploitation.chauffeur.feuilleRoute}/add-new-roadmap`);
  };
  const handleOldRoadMapsClick = (row: IRoadmap) => {
    router.push(
      `${paths.dashboard.exploitation.chauffeur.feuilleRoute}/old-roadmaps/${row.driverId}`
    );
  };
  const handleContactClick = (roadmap: IRoadmap) => {
    setSelectedRoadmap(roadmap);
    setContactDialogOpen(true);
  };
  const handleMethodSelect = (method: 'email' | 'sms' | 'internalChat') => {
    setContactMethod(method);
    setContactDialogOpen(false);
  };
  const updateRoadMapStatus = useRoadMapStore((state) => state.updateRoadMapStatus);
  const handleManualStatusChange = async (row: IRoadmap, newStatus: string) => {
    try {
      console.log('Changement de statut manuel', row.id, newStatus);
      await updateRoadMapStatus(Number(row.id), newStatus);
      console.log('Statut mis à jour avec succès');
      // optionnel : mets à jour localement si tu veux un effet immédiat
    } catch (e) {
      console.log('Erreur lors de la mise à jour du statut');
    }
  };

  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={handleManualStatusChange}
        onClickOldRoadMaps={handleOldRoadMapsClick}
        onClickContact={handleContactClick}
      />
    ),
    [
      table,
      handleEdit,
      handleCopy,
      handleView,
      tableHead,
      handleStatusChange,
      handleOldRoadMapsClick,
    ]
  );

  const isList = activeTab === 'list';

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

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

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

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

      <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 ? (
          <>
            <TableManager
              filteredData={validatedRoadMap}
              table={table}
              tableHead={tableHead}
              notFound={notFound}
              filters={filters}
              onFilterChange={handleFilterChange}
              renderRow={renderRow}
              loading={loading}
              count={totalElements}
            />
          </>
        ) : (
          <ValidateRoadmapView validatedRoadMapArgs={activeTabData?.content as ValidatedRoadMapArgs}></ValidateRoadmapView>
        )}
      </Box>
    </LocalizationProvider>
  );
}
