'use client';

import React, { useEffect, useState } from 'react';
import { Box, IconButton, Stack, Typography } from '@mui/material';
import { useRouter, useParams  } 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 OldRoadMapsTable from '../components/roadmap-list/old-roadmaps/old-roadmaps-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 TabsCustom from '@/shared/components/tabs/tabs-custom';
import { OldRoadMapByDriverFilterParams } from '@/shared/types/roadMap';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';

export default function OldRoadMapsView() {
const param = useParams();
  const router = useRouter();

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

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
  } = useOldRoadMapTable();

  const isList = activeTab === 'list';

useEffect(() => {
  if (!driverId) return;

  const newParams: OldRoadMapByDriverFilterParams = {
    page: table.page,
    size: table.rowsPerPage,
    sortBy: table.orderBy,
    sortDirection: table.order.toLowerCase() as 'asc' | 'desc',
    driverId: Number(driverId), 
  };

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


const { validatedRoadMap, getOldRoadMapByDriver, loading, error } = useRoadMapStore();
  const [params, setParams] = useState<OldRoadMapByDriverFilterParams>({
    page: 0,
    size: 5,
    sortBy: 'id',
    sortDirection: 'desc',
  });

 

  useEffect(() => {
    getOldRoadMapByDriver(params);
  }, [params]);
  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
        </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}
        />

      <OldRoadMapsTable
        table={table}
        filteredData={validatedRoadMap}
        filters={filters}
        tableHead={tableHead}
        notFound={notFound}
        dataToExport={dataToExport}
        activeTab={activeTab}
        onFilterChange={handleFilterChange}
        onResetFilters={handleResetFilters}
        onResetColumns={handleResetColumns}
        onColumnsChange={handleColumnsChange}
        handleEdit={handleEdit}
        handleCopy={handleCopy}
        handleView={handleView}
        loading={loading}
      />
    </Box>
  );
}
