import React, { useMemo } from 'react';
import { Box, Stack } from '@mui/material';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import { useInterventionTabs } from '../hooks/use-intervention-tabs';
import { useInterventionTable } from '../hooks/use-intervention-table';
import InterventionNewView from './interventions-new-view';
import InterventionRowView from './interventions-row-view';
import { TableType } from '@/shared/types/common';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faSquarePlus } from '@fortawesome/free-solid-svg-icons';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { Intervention } from '@/shared/types/fleet-management/service-provider';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useSnackbar } from 'notistack';

export default function InterventionListView() {

  const { enqueueSnackbar } = useSnackbar();

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

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

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

  const renderRow = (row: Intervention) => (
    <InterventionRowView
      key={row.id}
      row={row}
      columns={tableHead}
      handleEditIntervention={handleEdit}
      handleDetailsIntervention={handleView}
    />
  );

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

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

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', mt: 2 }}>

      <Stack
        flexGrow={0}
        direction="column"
        alignItems="flex-end"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
        sx={{ mb: 4 }}
      >
        <TableControlBar
          type={TableType.Intervention}
          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.Intervention}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />
      <ConditionalComponent isValid={activeTab === 'list'}
        defaultComponent={
          <InterventionNewView
            key={activeTab}
            intervention={activeTabData?.content as Intervention}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(force) => handleCancel(activeTab, force)}
            onEdit={handleEdit}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        }
      >
        <TableManager
          loading={loading}
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          sx={{ backgroundColor: 'primary.lighter' }}
          fixedHeight="calc(100vh - 200px)"
          onPageChange={onPageChange}
          page={page || 0}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage || 20}
          count={totalInterventions}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
