'use client';

import React, { useEffect, useRef, useMemo } from 'react';
import { Box, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import TrajetTabs from '../../../components/tabs/tabs-custom';
import { useTrajetTabs } from '../hooks/use-trajet-tabs';
import TrajetTable from '../components/trajet-table';
import { useTrajetTable } from '../hooks/use-trajet-table';
import TrajetForm from './trajet-new-view';
import { TableType } from '../../../types/common';
import { useSearchParams } from 'next/navigation';
import { TripCircuitDetails } from '@/shared/types/circuit';
import { useTripCircuitStore } from '@/shared/api/stores/circuit-service/tripCircuitStore';
import { enqueueSnackbar } from 'notistack';

export default function TrajetListView() {
  const searchParams = useSearchParams();
  const trajetId = searchParams.get('id');

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleEdit,
    handleView,
    handleCancel,
  } = useTrajetTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleStatusChange,
    dataToExport,
    getTripCircuit,
    loading,
    totalElements,
    handleExport,
  } = useTrajetTable();

  const isFirstRender = useRef(true);

  useEffect(() => {
  if (trajetId && isFirstRender.current) {
    getTripCircuit(trajetId, handleView);
    isFirstRender.current = false;
  }
  }, [getTripCircuit, handleView, trajetId]);

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

  const handleExportClick = async () => {
    try {
      await handleExport();
    } catch (error) {
      console.error("Erreur lors de l'exportation des trajets :", error);
    }
  };

  const exportOptions = useMemo(
    () => [
      {
        label: 'Exporter en csv',
        action: () => handleExportClick(),
      },
    ],
    [handleExportClick]
  );

  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.Trajet}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      <TrajetTabs
        type = {TableType.Trajet}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <TrajetTable
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleView={(trajetId) => getTripCircuit(trajetId, handleView)}
          onStatusChange={handleStatusChange}
          loading={loading}
          totalElements={totalElements}
        />
      ) : (
        <TrajetForm
          key={activeTabData?.id}
          trajet={activeTabData?.content as TripCircuitDetails}
          mode={activeTabData?.mode || 'view'}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
          tableHead={tableHead.slice(0, -1)}
          handleView={handleView}
           setDrawerMode={()=>{}}
        />
      )}
    </Box>
  );
}

