'use client';

import React, { useMemo, useState } from 'react';
import { Box, Stack, Typography } 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 ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { ColumnButton } from '@/shared/components/table/styles';
import CustomDrawer from '@/shared/components/drawer/custom-drawer';
import { useResponsive } from '@/hooks';
import InterventionListView from '../components/interventions-list-view';
import { useServiceProviderTabs } from '../hooks/use-service-provider-tabs';
import { useServiceProviderTable } from '../hooks/use-service-provider-table';
import ServiceProviderTableRow from './service-provider-table-row';
import { ServiceProvider } from '@/shared/types/fleet-management/service-provider';
import ServiceProviderForm from './service-provider-form';
import { useSnackbar } from 'notistack';

export default function SupplierTypeListView() {

  const { enqueueSnackbar } = useSnackbar();

  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const DRAWER_WIDTH = useResponsive("down", "lg") ? 600 : 800;

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

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

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

  const renderRow = (row: ServiceProvider) => (
    <ServiceProviderTableRow
      key={row.id}
      row={row}
      handleEditServiceProvider={handleEdit}
      handleDetailsServiceProvider={handleView}
      handleDuplicateServiceProvider={handleCopy}
      columns={tableHead.slice(0, -1)}
    />
  );

  const handleViewIntervention = () => {
    setIsDrawerOpen(true);
  };

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

  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 }}>
        <CustomTooltip title={"Gestion des interventions"} arrow>
          <ColumnButton variant="contained" onClick={handleViewIntervention}>
            Intervention
          </ColumnButton>
        </CustomTooltip>
        <TableControlBar
          type={TableType.ServiceProvider}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.filter(col => col.id !== 'action')}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      <CustomTabs
        type={TableType.ServiceProvider}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />
      <ConditionalComponent isValid={activeTab === 'list'}
        defaultComponent={
          <ServiceProviderForm
            key={activeTab}
            serviceProvider={activeTabData?.content as ServiceProvider}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(force) => handleCancel(activeTab, force)}
            onEdit={handleEdit}
            setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        }
      >
        <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={totalServiceProviders}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
      <CustomDrawer
        drawerWidth={DRAWER_WIDTH}
        open={isDrawerOpen}
        onClose={() => setIsDrawerOpen(false)}
      >
        <Typography
          variant="h5"
          sx={{
            my: 3,
            color: 'primary.main',
            fontWeight: (theme) => theme.typography.fontWeightBold,
          }}
        >
          Liste des interventions
        </Typography>
        <InterventionListView />
      </CustomDrawer>
    </Box>
  );
}