'use client';

import { useMemo, useState } from 'react';
import { Box, IconButton, 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_CIRCUIT_PREPARATION_TABLE_HEAD,
  INITIAL_CIRCUIT_PREPARATION_DATA,
  _mockRoutes,
  _circuitsPreparation,
  _mockCircuitRoutes,
} from '@/shared/_mock/_preparationCircuit';
import { IPreparationCircuit } from '@/shared/types/circuit';
import CircuitTableRow from './circuit-table-row';
import {
  AddButton,
  mainColor,
} from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import {
  faSquarePlus,
} from '@fortawesome/free-solid-svg-icons';
import CustomDrawer from '@/shared/components/drawer/custom-drawer';
import dynamic from 'next/dynamic';
import PreparationCircuitForm from './circuit-new-view';
import MapsControlBar from '@/shared/components/table/maps-control-bar';
import { MapType } from '@/shared/types/Maps';
import { useRouter } from '@/hooks/use-router';
import { paths } from '@/routes/paths';
import { useBoolean } from '@/hooks';
import MassUploadFile from '@/shared/components/mass-import/mass-upload-file';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
const MapView = dynamic(() => import('@/shared/components/google-maps/maps'), {
  ssr: false,
});

const circuitConfig: TableConfig<IPreparationCircuit> = {
  initialData: _circuitsPreparation,
  defaultTableHead: DEFAULT_CIRCUIT_PREPARATION_TABLE_HEAD,
};

const circuitTabsConfig: TabConfig<IPreparationCircuit> = {
  type: TableType.Circuit,
  listTitle: 'Visualisation des circuits',
  newItemTitle: 'Nouveau circuit',
  initialData: INITIAL_CIRCUIT_PREPARATION_DATA,
  getItemCode: (circuit) => circuit.intitule,
};

export default function PreparationCircuitListView() {
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const router = useRouter();
  const uploadFile = useBoolean(false);

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

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

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

  const renderRow = (row: IPreparationCircuit) => (
    <CircuitTableRow
      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 handleNavigation = () => {
    router.push(paths.dashboard.exploitation.preparation.chauffeur);
  };
  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.Circuit}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          withoutColumnSelector
          action={
            <MapsControlBar
              onImport={uploadFile.onTrue}
              onExport={() => void 0}
              onAdd={handleTabAdd}
              onViewList={handleViewList}
              label={TableType.Circuit}
              addLabel="Nouveau circuit"
            />
          }
        />
      </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 circuits
          </Typography>
            <CustomTooltip title={"Valider et passer à l'étape suivante"} arrow>
              <AddButton variant="contained" onClick={handleNavigation}>
                Valider
              </AddButton>
            </CustomTooltip>
        </Stack>
      ) : (
        <Stack
          direction="row"
          justifyContent="flex-end"
          sx={{mb:4}}
        >
          <CustomTooltip title={'Nouvelle Circuit'} arrow>
            <IconButton sx={mainColor} onClick={handleTabAdd}>
              <FontAwesome icon={faSquarePlus} width={18} />
            </IconButton>
          </CustomTooltip>
        </Stack>
      )}

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

      {isList ? (
        <MapView
          sx={{ borderTopLeftRadius: 0 }}
          height="calc(100vh - 250px)"
          routes={_mockCircuitRoutes}
          Submodule={MapType.CIRCUIT}
        />
      ) : (
        <PreparationCircuitForm
          key={activeTab}
          preparationCircuit={activeTabData?.content as IPreparationCircuit}
          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 circuits
        </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>
      {uploadFile.value ? 
        <MassUploadFile
          open={uploadFile.value} 
          onClose={uploadFile.onFalse}
        /> : <></>}
        <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
