'use client';

import React, { useMemo, useRef, useEffect, useState } from 'react';
import { Box, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import UsagerTabs from '../../../components/tabs/tabs-custom';
import { useUsagerTabs } from '../hooks/use-usager-tabs';
import { useUsagerTable } from '../hooks/use-usager-table';
import { TableType } from '../../../types/common';
import UsagerTable from '../components/usager-table';
import UsagerForm from './usager-new-view';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { IPassengerList, Representative } from '@/shared/types/passenger';
import { useSearchParams } from 'next/navigation';
import { enqueueSnackbar } from 'notistack';
import MapsControlBar from '@/shared/components/table/maps-control-bar';
import { useBoolean } from '@/hooks';
import MassUploadFile from '@/shared/components/mass-import/mass-upload-file';
import { TypeImport } from '@/shared/types/common';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';

export default function UsagerListView() {
  const searchParams = useSearchParams();
  const usagerId = searchParams.get('id');

  const isFirstRender = useRef(true);


  const { getPassengerById, downloadPassengersTemplate, importPassengers, exportingPassengersTemplateLoader } = usePassengerStore();
  const uploadFile = useBoolean(false);

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

  const {
    loading,
    error,
    totalPassengers,
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleStatusChange,
    dataToExport,
    handleExportPassengers,
  } = useUsagerTable();

  useEffect(() => {
    if (usagerId && isFirstRender.current) {
      const loadAndViewUsager = async () => {
        try {
          const usagerToView = await getPassengerById(usagerId);
          if (usagerToView) {
            handleView(usagerToView);
          }
        } catch (error: any) {
          enqueueSnackbar(error.message, { variant: 'error' });
        }
      };

      loadAndViewUsager();
      isFirstRender.current = false;
    }
  }, [handleView, usagerId, getPassengerById, filteredData]);

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

  const exportOptions = useMemo(
    () => [
      {
        label: 'Exporter en CSV',
        action: () => handleExportPassengers(),
      },
    ],
    [handleExportPassengers]
  );
  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 }}
      >
        <TableControlBar
          type={TableType.Usager}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
          buttonAddTitle="Nouvel usager"
          action={
            <MapsControlBar
              onImport={uploadFile.onTrue}
              label={TableType.Usager}
            />
          }
        />
      </Stack>

      <UsagerTabs
        type={TableType.Usager}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <UsagerTable
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleView={handleView}
          onStatusChange={handleStatusChange}
          loading={loading}
          totalPassengers={totalPassengers}
        />
      ) : (
        <UsagerForm
          key={activeTab}
          usager={activeTabData?.content as IPassengerList}
          originalRepresentatives={
            activeTabData?.originalContent?.representatives as Representative[]
          }
          hasUnsavedChanges={activeTabData?.hasUnsavedChanges}
          mode={activeTabData?.mode || 'view'}
          onClose={(isSaved) => handleCancel(activeTab, isSaved)}
          onEdit={handleEdit}
          tableHead={tableHead.slice(0, -1)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
          markTabAsSaved={markTabAsSaved}
          setTabReplaceCurrentTab={setTabReplaceCurrentTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
      {uploadFile.value ? (
        <MassUploadFile
          open={uploadFile.value}
          onClose={uploadFile.onFalse}
          type={TypeImport.PASSENGER}
          customBackendExport={downloadPassengersTemplate}
          customUpload={(file) => importPassengers(file)}
          isExportingTemplate={exportingPassengersTemplateLoader}
          allowedExtensions={[".xlsx", ".xls"]}
        />
      ) : (
        <></>
      )}
    </Box>
  );
}
