'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 {
  _passengerPreparation,
  DEFAULT_PASSENGER_PREPARATION_TABLE_HEAD,
  INITIAL_PASSENGER_PREPARATION_DATA,
} from '@/shared/_mock/_preparationUsager';
import { type TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { TableColumn, TableType, TypeImport } from '@/shared/types/common';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import PreparationUsagerTableRow from './usager-table-row';
import PreparationUsagerForm from './usager-new-view';
import { AddButton, mainColor } from '../../../../components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faSquarePlus } from '@fortawesome/free-solid-svg-icons';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import MapsControlBar from '@/shared/components/table/maps-control-bar';
import { IPreparationUsager } from '@/shared/types/usager';
import dynamic from 'next/dynamic';
import CustomDrawer from '@/shared/components/drawer/custom-drawer';
import { _mockPassengersRoutes, _mockRoutes } from '@/shared/_mock/_preparationCircuit';
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';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

const MapView = dynamic(() => import('@/shared/components/google-maps/maps'), {
  ssr: false,
});

const preparationUsagerConfig: TableConfig<IPreparationUsager> = {
  initialData: _passengerPreparation,
  defaultTableHead: DEFAULT_PASSENGER_PREPARATION_TABLE_HEAD as TableColumn[],
};

const preparationUsagerTabsConfig: TabConfig<IPreparationUsager> = {
  type: TableType.Usager,
  listTitle: 'Visualisation des usagers',
  newItemTitle: 'Nouvel usager',
  initialData: INITIAL_PASSENGER_PREPARATION_DATA,
  getItemCode: (usager) => usager.nom + ' ' + usager.prenom,
};

export default function PreparationUsagerListView() {
  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<IPreparationUsager>(preparationUsagerTabsConfig);

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

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

  const handleViewList = () => {
    setIsDrawerOpen(true);
  };
  const renderRow = (row: IPreparationUsager) => (
    <PreparationUsagerTableRow
      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.circuit);
  };

  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.Usager}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          withoutColumnSelector
          action={
            <MapsControlBar
              onImport={uploadFile.onTrue}
              onAdd={handleTabAdd}
              onViewList={handleViewList}
              label={TableType.Usager}
              addLabel="Nouvel usager"
            />
          }
        />
      </Stack>
      <ConditionalComponent
        isValid={isList}
        defaultComponent={
          <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>
        }
      >
        <Stack direction="row" justifyContent="space-between" sx={{ my: 1 }}>
          <Typography
            variant="h5"
            sx={{
              color: 'primary.main',
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Préparation des Usagers
          </Typography>
          <CustomTooltip title={"Valider et passer à l'étape suivante"} arrow>
            <AddButton variant="contained" onClick={handleNavigation}>
              Valider
            </AddButton>
          </CustomTooltip>
        </Stack>
      </ConditionalComponent>

      <TabsCustom
        type={TableType.Usager}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />
      <ConditionalComponent
        isValid={isList}
        defaultComponent={
          <PreparationUsagerForm
            key={activeTab}
            preparationUsager={activeTabData?.content as IPreparationUsager}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(forceClose) => handleCancel(activeTab, forceClose)}
            onEdit={handleEdit}
            tableHead={tableHead}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        }
      >
        <MapView
          sx={{ borderTopLeftRadius: 0 }}
          height="calc(100vh - 250px)"
          routes={_mockPassengersRoutes}
          Submodule={MapType.PASSENGER}
        />
      </ConditionalComponent>
      <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 usagers
        </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>
      <ConditionalComponent isValid={uploadFile.value}>
        <MassUploadFile
          open={uploadFile.value}
          onClose={uploadFile.onFalse}
          type={TypeImport.PASSENGER}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
