'use client';

import React, { useMemo, useRef, useEffect } 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 } from '@/shared/types/passenger';
import { useSearchParams } from 'next/navigation';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { enqueueSnackbar } from 'notistack';

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

  const { getPassengerById } = usePassengerStore();
  
  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,
    handleSave,
    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}
        />
      </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}
            hasUnsavedChanges={activeTabData?.hasUnsavedChanges}
            mode={activeTabData?.mode || 'view'} 
            onSave={handleSave}
            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)}
      />
    </Box>
  );
}

