'use client';

import React, { useEffect, useMemo, useRef } from 'react';
import { Box, Stack } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import ContractForm from './contract-new-view';
import { useContractTabs } from '../hooks/use-contract-tabs';
import { useContractTable } from '../hooks/use-contract-table';
import ContractTabs from '../../../components/tabs/tabs-custom';
import { ContractList } from '@/shared/types/contract';
import ContractTable from '../components/contract-table';
import { TableType } from '@/shared/types/common';
import { useSearchParams } from 'next/navigation';
import { _contracts } from '@/shared/_mock/_Contrat';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';

export default function ContratListView() {
  const searchParams = useSearchParams();
  const contratId = searchParams.get('id');
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useContractTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    dataToExport,
    totalContracts,
    onPageChange,
    page,
    onRowsPerPageChange,
    rowsPerPage,
    sortBy,
    sortDirection,
    handleStartExportContracts
  } = useContractTable();
  const isFirstRender = useRef(true);

  useEffect(() => {
    if (contratId && isFirstRender.current) {
      const contractToView = filteredData.find((contract: ContractList) => contract.id === contratId);
      if (contractToView) {
        handleView(contractToView);
      }
      isFirstRender.current = false;
    }
  }, [handleView, contratId, filteredData]);

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


  const exportOptions = useMemo(() => [
    {
      label: "Exporter en CSV",
      action: () => handleStartExportContracts()
    }
  ], [handleStartExportContracts]);

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

      <ContractTabs
        type={TableType.Contrat}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <ContractTable
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleView={handleView}
          totalContracts={totalContracts}
          onPageChange={onPageChange}
          page={page || 0}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPage={rowsPerPage || 20}
          sortBy={sortBy || 'id'}
          sortDirection={sortDirection || 'desc'}
        />
      ) : (
        <ContractForm
          key={activeTab}
          contrat={activeTabData!.content as ContractList}
          mode={activeTabData?.mode || 'view'}
          onClose={(value) => handleCancel(activeTab, value)}
          onEdit={handleEdit}
          tableHead={tableHead.slice(0, -1)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <ConfirmDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
        title="Modifications non sauvegardées"
        content="Des modifications non sauvegardées seront perdues si vous fermez cet onglet. Voulez-vous continuer ?"
        confirmButtonText="Fermer sans sauvegarder"
        cancelButtonText="Annuler"
        confirmButtonColor="error"
      />
    </Box>
  );
}

