'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
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 SuiviTrajetTableRow from './suivi-trajet-table-row';
import SuiviTrajetForm from './suivi-trajet-new-view';
import { IRouteTracking } from '@/shared/types/suivi-trajet';
import {
  _routeTracking,
  DEFAULT_ROUTE_TRACKING_TABLE_HEAD,
  INITIAL_ROUTE_TRACKING_DATA,
} from '@/shared/_mock/_suiviTrajet';
import { DailyTripDTO, DailyTripListParams, TripCircuitDetails } from '@/shared/types/circuit';
import { useTripCircuitStore } from '@/shared/api/stores/circuit-service/tripCircuitStore';
import { da } from 'date-fns/locale';
import { useTrajetTabs } from '@/shared/sections/trajet/hooks/use-trajet-tabs';
import { enqueueSnackbar } from 'notistack';
import { useSearchParams } from 'next/navigation';
import TrajetForm from '@/shared/sections/trajet/view/trajet-new-view';
import { usePlanningDriverStore } from '@/shared/api/stores/planningDriverStore';
import DriverTripForm from './suivi-trajet-new-view';

const suiviTrajetConfig: TableConfig<DailyTripDTO> = {
  initialData: [],
  defaultTableHead: DEFAULT_ROUTE_TRACKING_TABLE_HEAD,
};

const suiviTrajetTabsConfig: TabConfig<DailyTripDTO> = {
  type: TableType.SuiviTrajet,
  listTitle: 'Liste des trajet',
  newItemTitle: 'Nouveau trajet',
  initialData: INITIAL_ROUTE_TRACKING_DATA,
  getItemCode: (suiviTrajet) => suiviTrajet.title,
};
const joursMap: Record<string, string> = {
  LU: 'Lun',
  MA: 'Mar',
  ME: 'Mer',
  JE: 'Jeu',
  VE: 'Ven',
  SA: 'Sam',
  DI: 'Dim',
};
export function formatDateFromTitle(title: string, dateStr?: string): string {
  if (!title) return '';
  const parts = title.split('-');
  const timeMatch = title.match(/\d{2}:\d{2}(:\d{2})?/);
  const hour = timeMatch ? timeMatch[0].slice(0, 5) : '';
  let jour = '';

  if (dateStr) {
    const date = new Date(dateStr);
    if (!isNaN(date.getTime())) {
      const jours = ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'];
      const dayIndex = date.getDay();
      jour = jours[dayIndex];
    }
  }

  if (!jour) {
    const jourAbbr = parts.find((p) => joursMap[p]);
    jour = jourAbbr ? joursMap[jourAbbr] : '';
  }

  return `${jour} ${hour}`;
}

export default function SuiviTrajetListView() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
  } = useTrajetTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    dataToExport,
    handleStatusChange,
  } = useTableManager<DailyTripDTO>(suiviTrajetConfig);
  const { getAllDailyTrips, dailyTrips, loading,totalElements, error } = usePlanningDriverStore();
  const {  getTripCircuitById } = useTripCircuitStore();
  const getTripCircuit = useCallback(
    async (id: string, handleView: (details: TripCircuitDetails) => void) => {
      try {
        const details = await getTripCircuitById(id);
        if (details) {
          handleView(details);
        }
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la récupération du détail', {
          variant: 'error',
        });
      }
    },
    [getTripCircuitById]
  );

 
 useEffect(() => {
     const newParams: DailyTripListParams = {
       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]);
 
   const [params, setParams] = useState<DailyTripListParams>({
     page: 0,
     size: 5,
     sortBy: 'id',
     sortDirection: 'desc',
   });
  useEffect(() => {
    getAllDailyTrips(params);
  }, [params]);

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

  const searchParams = useSearchParams();
  const trajetId = searchParams.get('id');
  const isFirstRender = useRef(true);

  useEffect(() => {
    if (trajetId && isFirstRender.current) {
      getTripCircuit(trajetId, handleView);
      isFirstRender.current = false;
    }
  }, [getTripCircuit, handleView, trajetId]);
  const renderRow = useCallback(
    (row: DailyTripDTO) => {
      return (
        <SuiviTrajetTableRow
          key={row.id}
          dense={table.dense}
          row={{
            ...row,
            date: formatDateFromTitle(row.title, row.date),
          }}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleDetails={(trajetId) => getTripCircuit(trajetId, handleView)}
          selected={table.selected.includes(row.id)}
          onSelectRow={() => table.onSelectRow(row.id)}
          columns={tableHead}
          onStatusChange={handleStatusChange}
        />
      );
    },
    [table, handleEdit, handleCopy, handleView, tableHead, handleStatusChange]
  );

  const isList = activeTab === 'list';

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.SuiviTrajet}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
        />
      </Stack>

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

      {isList ? (
        <TableManager
          filteredData={dailyTrips}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          loading={loading}
          count={totalElements}        />
      ) : (
        <DriverTripForm
          trajet={activeTabData?.content as TripCircuitDetails}
          handleView={handleView}
        />
      )}
    </Box>
  );
}
