'use client';

import React, { useEffect, useState } from 'react';
import { Box, Stack, Typography } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import { TableType } from '@/shared/types/common';
import TableControlBar from '@/shared/components/table/table-control-bar';

import TabsCustom from '@/shared/components/tabs/tabs-custom';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useSubmittedRoadMapTabs } from '../components/hooks/use-submitted-roadmap-tabs';
import SubmittedRoadMapTable from '../components/submitted-roadmap/submitted-roadmap-table';
import { useRouter } from '@/hooks/use-router';
import { paths } from '@/routes/paths';
import { IActiveDriver, IDriver, ISubmittedRoadmap } from '@/shared/types/driver';
import ContactMethodDialog from '../components/roadmap-list/old-roadmaps/contact-dialog';
import SendEmailDialog from '../components/roadmap-list/old-roadmaps/contact-email-dialog';
import SendSmsDialog from '../components/roadmap-list/old-roadmaps/contact-sms-dialog';
import CreatRoadMapPage from '../components/submitted-roadmap/create-roadmap/create-roadmap-page';
import { Dayjs } from 'dayjs';
import { _drivers } from '@/shared/_mock/_drivers';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import { INITIAL_SUBMITTED_ROADMAP_DATA, SubmittedRoadMapDTO, SubmittedRoadMapFilterParams } from '@/shared/types/roadMap';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { DEFAULT_SUBMITTED_ROADMAP_TABLE_HEAD } from '@/shared/_mock/_roadMap';
import NewRoadmapDialog from '../components/submitted-roadmap/submitted-roadmap-dialog';

export default function SubmittedRoadMapView() {

  const {
    submittedRoadMaps,
    getAllSubmittedRoadMaps,
    loading,
    error,
  } = useRoadMapStore();
  


  const tableConfig: TableConfig<SubmittedRoadMapDTO> = {
    initialData: submittedRoadMaps,
    type: 'feuille de route soumise',
    defaultTableHead: DEFAULT_SUBMITTED_ROADMAP_TABLE_HEAD,
  };

  const tabConfig: TabConfig<SubmittedRoadMapDTO> = {
    type: TableType.DriverRoadmap,
    listTitle: 'Liste de feuilles de route',
    newItemTitle: 'Anciennes feuilles de route',
    initialData: INITIAL_SUBMITTED_ROADMAP_DATA,
    getItemCode: (roadmap) => roadmap.id,
  };

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    dataToExport,
  } = useTableManager<SubmittedRoadMapDTO>(tableConfig);

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleCopy,
    handleEdit,
    handleView
  } = useTabsManager(tabConfig);

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

  useEffect(() => {
    const newParams: SubmittedRoadMapFilterParams = {
      page: table.page,
      size: table.rowsPerPage,
      sortBy: 'id',
      sortDirection: 'desc',
    };
  
    const filterParams: Partial<SubmittedRoadMapFilterParams> = {};
    Object.entries(filters as Record<string, { value: string }>).forEach(([key, { value }]) => {
      if (value) {
        if (key === 'isSubmitted') {
          const lowered = value.toLowerCase().trim();
          if (['soumise', 'true'].includes(lowered)) {
            filterParams.isSubmitted = true;
          } else if (['non', 'n', 'non soumise', 'false'].includes(lowered)) {
            filterParams.isSubmitted = false;
          }
        } else {
          (filterParams as any)[key] = value;
        }
      }
    });
  
    setParams({ ...newParams, ...filterParams });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

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

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

  const handleContactClick = (roadmap: SubmittedRoadMapDTO) => {
    setSelectedRoadmap(roadmap);
    setContactDialogOpen(true);
  };
  
  const handleMethodSelect = (method: 'email' | 'sms' | 'internalChat') => {
    setContactMethod(method);
    setContactDialogOpen(false);
  };

  const router = useRouter();

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

  

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

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

  return (
    <>

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

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

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

    
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        ...(isList && {
          height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
        }),
      }}
    >
      <ConditionalComponent isValid={isList}>
        <Typography
          variant="h5"
          sx={{
            color: 'primary.main',
            fontWeight: (theme) => theme.typography.fontWeightBold,
            
          }}
        >
          Liste des feuilles de route soumises
        </Typography>
      </ConditionalComponent>
    
        <Stack direction="row" spacing={{ xs: 0.5, sm: 1 }} justifyContent="flex-end">
          <TableControlBar
            type={TableType.DriverRoadmap}
            activeTab={activeTab}
            handleTabAdd={() => setIsNewRoadmapDialogOpen(true)}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -2)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
          />
        </Stack>
        <TabsCustom
          type={TableType.Driver}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />
      <ConditionalComponent isValid={isList} defaultComponent={<CreatRoadMapPage activeTabData={activeTabData?.content as SubmittedRoadMapDTO} />}>
        <SubmittedRoadMapTable
          table={table}
          filteredData={filteredData}
          filters={filters}
          tableHead={tableHead}
          notFound={notFound}
          dataToExport={dataToExport}
          activeTab={activeTab}
          activeTabData={activeTabData?.content as SubmittedRoadMapDTO}
          onFilterChange={handleFilterChange}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleView={handleView}
          handleOldRoadMapsClick={handleOldRoadMapsClick}
          handleContact={handleContactClick}
        />
      </ConditionalComponent>
    </Box>
      <NewRoadmapDialog
        open={isNewRoadmapDialogOpen}
        onClose={() => setIsNewRoadmapDialogOpen(false)}
        onSend={handleNewRoadmap}
      />
    </>
  );
}
