'use client';

import { useEffect, 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 { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { type TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { TableType } from '@/shared/types/common';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import {
  DEFAULT_DRIVER_PREPARATION_TABLE_HEAD,
  INITIAL_DRIVER_PREPARATION_DATA,
  _driversPreparation,
} from '@/shared/_mock/_preparationDriver';
import type { IPreparationDriver } from '@/shared/types/driver';
import { AddButton } from '@/shared/components/table/styles';
import CustomDrawer from '@/shared/components/drawer/custom-drawer';
import dynamic from 'next/dynamic';
import MapsControlBar from '@/shared/components/table/maps-control-bar';
import DriverTableRow from './driver-table-row';
import PreparationDriverForm from './driver-new-view';
import { _mockRoutes } from '@/shared/_mock/_preparationCircuit';
import { MapType } from '@/shared/types/Maps';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
const MapView = dynamic(() => import('@/shared/components/google-maps/maps'), {
  ssr: false,
});

const driverConfig: TableConfig<IPreparationDriver> = {
  initialData: _driversPreparation,
  defaultTableHead: DEFAULT_DRIVER_PREPARATION_TABLE_HEAD,
};

const driverTabsConfig: TabConfig<IPreparationDriver> = {
  type: TableType.Driver,
  listTitle: 'Visualisation des chauffeurs',
  newItemTitle: 'Nouveau chauffeur',
  initialData: INITIAL_DRIVER_PREPARATION_DATA,
  getItemCode: (driver) => `${driver.nom} ${driver.prenom}`,
};

export default function PreparationDriverListView() {
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<IPreparationDriver>(driverTabsConfig);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport
  } = useTableManager<IPreparationDriver>(driverConfig);

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

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

  const renderRow = (row: IPreparationDriver) => (
    <DriverTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleEdit}
      handleCopy={handleCopy}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  );

  const isList = activeTab === 'list';
  const DRAWER_WIDTH = 680;

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
        width: isDrawerOpen ? `calc(100% - ${DRAWER_WIDTH}px)` : undefined,
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.Driver}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          withoutColumnSelector
          action={
            <MapsControlBar
              onImport={undefined}
              onAdd={undefined}
              onViewList={handleViewList}
              label={TableType.Driver}
              addLabel="Nouveau chauffeur"
            />
          }
        />
      </Stack>

      {isList ? (
        <Stack direction="row" justifyContent="space-between" sx={{ my: 1 }}>
          <Typography
            variant="h5"
            sx={{
              color: 'primary.main',
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Préparation des chauffeurs
          </Typography>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <CustomTooltip title={'Terminer la Préparation'} arrow>
              <AddButton variant="contained" onClick={() => void 0}>
                Terminer la Préparation
              </AddButton>
            </CustomTooltip>
          </Box>
        </Stack>
      ) : (
        <></>
      )}

      <TabsCustom
        type={TableType.Driver}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {isList ? (
        <MapView
          sx={{ borderTopLeftRadius: 0 }}
          height="calc(100vh - 250px)"
          routes={_mockRoutes}
          Submodule={MapType.DRIVER}
        />
      ) : (
        <PreparationDriverForm
          key={activeTab}
          preparationDriver={activeTabData?.content as IPreparationDriver}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={(forceClose) => handleCancel(activeTab, forceClose)}
          onEdit={handleEdit}
          tableHead={tableHead}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <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 chauffeurs
        </Typography>

        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          isDrawer
          sx={{ backgroundColor: 'primary.lighter', pr: 0 }}
          fixedHeight="calc(100vh - 136px)"
          isWithoutTabs
        />
      </CustomDrawer>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
