'use client';

import React, { 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 { TableType } from '@/shared/types/common';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useSnackbar } from 'notistack';
import { VehicleIncident } from '@/shared/types/fleet-management/vehicle-incident';
import VehicleIncidentTableRow from './vehicle-incident-table-row';
import { useVehicleIncidentTabs } from '../hooks/use-vehicle-incident-tabs';
import { useVehicleIncidentTable } from '../hooks/use-vehicle-incident-table';
import VehicleIncidentForm from './vehicle-incident-new-view';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';


export default function VehicleIncidentListView() {

  const { enqueueSnackbar } = useSnackbar();

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

  const {
    error,
    loading,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    totalVehicleIncidents,
    sortBy,
    sortDirection,
    handleStartCsvExportVehicleIncidents
  } = useVehicleIncidentTable();

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

  const renderRow = (row: VehicleIncident) => (
    <VehicleIncidentTableRow
      key={row.id}
      row={row}
      handleEditIncident={handleEdit}
      handleDetailsIncident={handleView}
      columns={tableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
    />
  );

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

  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.VehicleIncident}
          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.VehicleIncident}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      <ConditionalComponent isValid={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={totalVehicleIncidents}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      </ConditionalComponent>

      <ConditionalComponent isValid={activeTab !== 'list'}>
        <VehicleIncidentForm
          key={activeTab}
          vehicleIncident={activeTabData?.content as VehicleIncident}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={(isSaved) => handleCancel(activeTab, isSaved)}
          onEdit={handleEdit}
          tableHead={tableHead}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      </ConditionalComponent>

      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}