'use client';

import React, { useEffect, useMemo, useRef } from 'react';
import { Box, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useVehicleTabs } from '../hooks/use-vehicle-tabs';
import { useVehicleTable } from '../hooks/use-vehicle-table';
import { TableType } from '@/shared/types/common';
import { IVehicle } from '@/shared/types/flottes/vehicule';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import VehicleForm from './vehicle-new-view';
import VehicleTableRow from './vehicle-table-row';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { Vehicle, VehicleListResponse } from '@/shared/types/fleet-management/vehicle';
import { useSnackbar } from 'notistack';


export default function VehicleListView() {

  const { enqueueSnackbar } = useSnackbar();

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useVehicleTabs();

  const {
    error,
    loading,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalVehicles,
    sortBy,
    sortDirection,
    handleStartCsvExportVehicles
  } = useVehicleTable();

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

  const renderRow = (row: VehicleListResponse) => (
    <VehicleTableRow
      key={row.id}
      row={row}
      handleCopyVehicle={handleCopy}
      handleEditVehicle={handleEdit}
      handleDetailsVehicle={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  )

  const exportOptions = useMemo(() => [
    {
      label: "Lancer l'export en CSV",
      action: () => handleStartCsvExportVehicles()
    }
  ], [handleStartCsvExportVehicles]);

  if (error) {
    enqueueSnackbar(error, { variant: 'error' })
  }

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

      <CustomTabs
        type={TableType.Vehicle}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <TableManager
          loading={loading}
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          onPageChange={onPageChange}
          page={page || 0}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage || 20}
          count={totalVehicles}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      ) : (
        <VehicleForm
          key={activeTabData?.id}
          vehicle={activeTabData?.content as VehicleListResponse}
          mode={activeTabData?.mode || 'view'}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
          tableHead={tableHead}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}

