'use client';

import React, { useEffect, useState } from 'react';
import { Box, IconButton, Stack, Typography } from '@mui/material';
import { useRouter, useSearchParams } from 'next/navigation';
import { HEADER } from '@/layouts/config-layout';
import { useOldRoadMapTabs } from '../components/hooks/use-old-roadmap-tabs';
import { useOldRoadMapTable } from '../components/hooks/use-old-roadmap-table';
import TableControlBar from '@/shared/components/table/table-control-bar';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import { TableType } from '@/shared/types/common';
import FontAwesome from '@/shared/components/fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { WhiteIconButtonStyle } from '@/shared/theme/css';
import OldSubmittedRoadMapsTable from '../components/roadmap-list/old-submitted-roadmap/old-roadmaps-table';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import { IOldRoadmap, OldSubmittedRoadMapFilterParams } from '@/shared/types/driver';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { DEFAULT_OLD_ROADMAPS_TABLE_HEAD } from '@/shared/_mock/_roadMap';

export default function OldSubmittedRoadMapsView() {
  const router = useRouter();

  const {
    oldSubmittedRoadMaps,
    getOldSubmittedRoadMaps,
    loading,
    error,
    totalElements
  } = useRoadMapStore();

  const tableConfig: TableConfig<IOldRoadmap> = {
    initialData: oldSubmittedRoadMaps,
    defaultTableHead: DEFAULT_OLD_ROADMAPS_TABLE_HEAD,
  };

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

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

  const isList = activeTab === 'list';

  const searchParams = useSearchParams();
  const driverIdParam = searchParams.get('driverId');

  const [params, setParams] = useState<OldSubmittedRoadMapFilterParams>({
    driverId: Number(driverIdParam), 
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'desc',
  });
  
  useEffect(() => {
    const newParams: OldSubmittedRoadMapFilterParams = {
      driverId: Number(driverIdParam), 
      page: table.page,
      size: table.rowsPerPage,
      sortBy: table.orderBy || 'id',
      sortDirection: table.order === 'asc' ? 'asc' : 'desc',
    };
  
    const filterParams: Partial<OldSubmittedRoadMapFilterParams> = {};
    Object.entries(filters as Record<string, { value: string }>).forEach(([key, { value }]) => {
      if (value) {
        switch (key) {
          case 'totalHours':
              filterParams.totalHours = parseFloat(value.trim());
            break;
          case 'date':
            filterParams.date = value.trim();
            break;
          case 'name':
            filterParams.name = value.trim();
            break;
          default:
            (filterParams as any)[key] = value;
        }
      }
    });
  
    setParams({ ...newParams, ...filterParams });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);
  
  useEffect(() => {
    if (driverIdParam) {
      getOldSubmittedRoadMaps(params);
    }
  }, [params, driverIdParam]);

  const activeTabData = React.useMemo(() => {
    return tabs.find(tab => tab.id === activeTab);
  }, [tabs, activeTab]);
  
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Box sx={{ px: 2, py: 1 }}>
        <CustomTooltip title="Retour à la page précédente" arrow>
          <IconButton sx={WhiteIconButtonStyle} onClick={() => router.back()}>
            <FontAwesome icon={faArrowLeft} width={18} />
          </IconButton>
        </CustomTooltip>
      </Box>

      <Typography
          variant="h5"
          sx={{
            color: 'primary.main',
            fontWeight: (theme) => theme.typography.fontWeightBold,
          }}
        >
          Anciennes feuilles de route soumises
        </Typography>

        <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
        <TableControlBar
            type={TableType.DriverRoadmap}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
          />
          </Stack>

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

      <OldSubmittedRoadMapsTable
        table={table}
        filteredData={filteredData}
        filters={filters}
        tableHead={tableHead}
        notFound={notFound}
        dataToExport={dataToExport}
        activeTab={activeTab}
        activeTabData={activeTabData?.content as IOldRoadmap}
        onFilterChange={handleFilterChange}
        onResetFilters={handleResetFilters}
        onResetColumns={handleResetColumns}
        onColumnsChange={handleColumnsChange}
        handleEdit={handleEdit}
        handleCopy={handleCopy}
        handleView={handleView}
      />
    </Box>
  );
}
