'use client';

import React, { useEffect, useRef } from 'react';
import { Box, CircularProgress, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useAvenantTabs } from '../hooks/use-avenant-tabs';
import { useAvenantTable } from '../hooks/use-avenant-table';
import AvenantTabs from '../../../components/tabs/tabs-custom';
import { TableType } from '@/shared/types/common';
import { useSearchParams } from 'next/navigation';
import { IAvenant } from '@/shared/types/circuit';
import AvenantForm from './avenant-new-view';
import TableManager from '@/shared/components/table/table-manager';
import AvenantTableRow from './avenant-table-row';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useAmendmentStore } from '@/shared/api/stores/amendmentStore';

export default function AvenantListView() {
  const searchParams = useSearchParams();
  const avenantId = searchParams.get('id');
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useAvenantTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport,
    loading: tableLoading,
    error: tableError,
    handleStartExportAvenants,
  } = useAvenantTable();

  const { getAmendmentById, amendment, loading: amendmentLoading } = useAmendmentStore();
  const isFirstRender = useRef(true);

  // Export options for backend export
  const exportOptions = [
    {
      label: 'Exporter en CSV',
      action: handleStartExportAvenants,
    },
  ];

  useEffect(() => {
    if (avenantId && isFirstRender.current) {
      getAmendmentById(avenantId);
      isFirstRender.current = false;
    }
  }, [getAmendmentById, avenantId]);

  useEffect(() => {
    if (amendment && avenantId) {
      const amendmentData = amendment.amendment;
      const mappedAvenant: IAvenant = {
        id: amendmentData.id,
        dateApplication: amendmentData.applicationDate,
        etat: amendmentData.status === 'controle' ? 'controle' : 'non_controle',
        codeCircuit: amendmentData.circuitCode || '',
        codeAvenant: amendmentData.amendmentCode,
        intitule: amendmentData.title,
        objetAvenant: amendmentData.amendmentPurpose || '',
        type: amendmentData.type || '',
        dateFin: amendmentData.endDate || '',
        etablissement: amendmentData.establishment || '',
        chauffeur: amendmentData.driver,
        departement: amendmentData.company,
        clientDO: amendmentData.clientDO,
        isActive: amendmentData.active,
        objet: amendmentData.purpose || '',
      };
      handleView(mappedAvenant);
    }
  }, [amendment, avenantId, handleView]);

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

  const renderRow = (row: IAvenant) => (
    <AvenantTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEditAvenant={handleEdit}
      handleDetailsAvenant={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
    />
  );

  if (tableLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
        <CircularProgress />
      </Box>
    );
  }

  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.Avenant}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      <AvenantTabs
        type={TableType.Avenant}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
        />
      ) : (
        amendmentLoading && activeTabData?.content && typeof activeTabData.content !== 'string' && activeTabData.content.id === avenantId ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
            <CircularProgress />
          </Box>
        ) : (
          <AvenantForm
            isMainTable
            avenant={activeTabData?.content as IAvenant}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(isSaved) => handleCancel(activeTab, isSaved)}
            onEdit={handleEdit}
            tableHead={tableHead.slice(0, -1)}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        )
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}
