'use client';

import React, { useMemo, 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 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 { AmendmentCircuit } from '@/shared/types/ammendment-circuit';

export default function AvenantListView() {
  const searchParams = useSearchParams();
  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,
    totalElements,
    handleExport,
  } = useAvenantTable();

  const isFirstRender = useRef(true);


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

  const renderRow = (row: AmendmentCircuit) => (
    <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,-2)}
      onStatusChange={(row, newStatus, field) =>
        handleStatusChange(row, newStatus, field as keyof AmendmentCircuit)
      }
      loading={tableLoading}
    />
  );

  const exportOptions = useMemo(
    () => [
      {
        label: 'Exporter en csv',
        action: () => handleExport(),
      },
    ],
    [handleExport]
  );

  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}
              loading={tableLoading}
              count={totalElements}
            />
          </>
      ) : (
        <AvenantForm
          isMainTable
          avenant={activeTabData?.content as AmendmentCircuit}
          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>
  );
}
