'use client';

import React, { useEffect } from 'react';
import { Box, Stack, Tabs, Tab } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useCandidatureTabs } from '../hooks/use-candidature-tabs';
import { useCandidatureTable } from '../hooks/use-candidature-table';
import { useFormulaireTable } from '../hooks/use-formulaire-table';
import { useFormulaireTabs } from '../hooks/use-formulaire-tabs';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import CandidatureTable from '../components/candidature/candidature-table';
import CandidatureDetailsForm from '../components/candidature/candidature-details-form';
import CandidatureFormulaire from '../components/formulaire/candidature-formulaire';
import FormulaireDetailsForm from '../components/formulaire/formulaire-details-form';
import { ICandidature, CandidatureTab, IFormulaire } from '@/shared/types/candidature';
import { TableType } from '@/shared/types/common';
import { StyledFilterTabs } from '@/shared/theme/css';
import FormulaireTable from '../components/formulaire/candidature-formulaire';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

interface CandidatureListViewProps {
  defaultType?: 'Candidature chauffeur' | 'Candidature sédentaire';
}

export default function CandidatureListView({ defaultType }: CandidatureListViewProps) {
  const {
    tabs,
    activeTab,
    activeMainTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleMainTabChange,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useCandidatureTabs(defaultType);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    handleStatusChange
  } = useCandidatureTable(activeMainTab, defaultType);

  const {
    table: formulaireTable,
    filteredData: formulaireFilteredData,
    filters: formulaireFilters,
    tableHead: formulaireTableHead,
    notFound: formulaireNotFound,
    handleFilterChange: handleFormulaireFilterChange,
    handleResetFilters: handleFormulaireResetFilters,
    handleResetColumns: handleFormulaireResetColumns,
    handleColumnsChange: handleFormulaireColumnsChange,
    handleSave: handleFormulaireSave,
    dataToExport: formulaireDataToExport,
    handleStatusChange: handleFormulaireStatusChange,
    handleDelete: handleFormulaireDelete,
  } = useFormulaireTable();

  // Add Formulaire tabs
  const {
    tabs: formulaireTabs,
    activeTab: activeFormulaireTab,
    handleTabClose: handleFormulaireTabClose,
    handleTabChange: handleFormulaireTabChange,
    handleTabAdd: handleFormulaireTabAdd,
    handleEdit: handleFormulaireEdit,
    handleView: handleFormulaireView,
    handleCancel: handleFormulaireCancel,
    setTabHasUnsavedChanges: setFormulaireTabHasUnsavedChanges,
    showConfirmDialog: showFormulaireConfirmDialog,
    setShowConfirmDialog: setFormulaireShowConfirmDialog,
    handleConfirmDialogAction: handleFormulaireConfirmDialogAction,
    updateTabContent: updateFormulaireTabContent,
  } = useFormulaireTabs();

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

  const activeFormulaireTabData = React.useMemo(() => {
    return formulaireTabs.find((tab) => tab.id === activeFormulaireTab);
  }, [formulaireTabs, activeFormulaireTab]);

  const handleTabChangeWrapper = (event: React.SyntheticEvent, newValue: CandidatureTab) => {
    handleMainTabChange(newValue);
  };

  const isFormulaire = activeMainTab === CandidatureTab.Formulaire;

  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 }}
      >
        {activeMainTab !== CandidatureTab.Formulaire ? (
          <TableControlBar
            type={TableType.Candidature}
            handleTabAdd={activeMainTab !== CandidatureTab.ATraiter ? undefined : handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
          />
        ) : (
          <TableControlBar
            type={TableType.Formulaire}
            handleTabAdd={handleFormulaireTabAdd}
            activeTab={activeFormulaireTab}
            onResetFilters={handleFormulaireResetFilters}
            onResetColumns={handleFormulaireResetColumns}
            onColumnsChange={handleFormulaireColumnsChange}
            initialColumns={formulaireTableHead.slice(0, -1)}
            onFilters={handleFormulaireFilterChange}
            filteredData={formulaireDataToExport}
          />
        )}
      </Stack>
      <StyledFilterTabs
        value={activeMainTab}
        onChange={handleTabChangeWrapper}
        sx={{ mb: 2, mt: 1 }}
      >
        <Tab label="Tous" value={CandidatureTab.Tous} />
        <Tab label="À traiter" value={CandidatureTab.ATraiter} />
        <Tab label="Retenus" value={CandidatureTab.Retenus} />
        <Tab label="Validées" value={CandidatureTab.Tableau} />
        <Tab label="Refusés et Blacklistés" value={CandidatureTab.RefusesBlacklistes} />
        <Tab 
          label="RDV de la semaine" 
          value={CandidatureTab.RdvSemaine} 
          sx={{ 
            marginLeft: 'auto',
            pl: 2 
          }} 
        />
        <Tab label="Absent RDV" value={CandidatureTab.AbsentRdv} />
        <Tab label="Formulaire" value={CandidatureTab.Formulaire} />
      </StyledFilterTabs>


      {!isFormulaire ? (
        <TabsCustom
          type={TableType.Candidature}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />
      ) : (
        <TabsCustom
          type={TableType.Formulaire}
          tabs={formulaireTabs}
          activeTab={activeFormulaireTab}
          handleTabChange={handleFormulaireTabChange}
          handleTabClose={handleFormulaireTabClose}
        />
      )}

      {isFormulaire ? (
        activeFormulaireTab === 'list' ? (
          <FormulaireTable
            filteredData={formulaireFilteredData}
            table={formulaireTable}
            tableHead={formulaireTableHead}
            notFound={formulaireNotFound}
            filters={formulaireFilters}
            onFilterChange={handleFormulaireFilterChange}
            handleEdit={handleFormulaireEdit}
            handleView={handleFormulaireView}
            handleDelete={handleFormulaireDelete}
          />
        ) : (
          <FormulaireDetailsForm
            key={activeFormulaireTab}
            formulaire={activeFormulaireTabData?.content as IFormulaire}
            mode={activeFormulaireTabData?.mode || 'view'}
            onSave={handleFormulaireSave}
            onClose={(forceClose) => handleFormulaireCancel(activeFormulaireTab, forceClose)}
            onEdit={handleFormulaireEdit}
            tableHead={formulaireTableHead}
            updateTabContent={updateFormulaireTabContent}
            tabId={activeFormulaireTab}
          />
        )
      ) : (
        activeTab === 'list' ? (
          <CandidatureTable
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            handleEdit={handleEdit}
            handleView={handleView}
            activeTab={activeMainTab}
            onStatusChange={handleStatusChange}
          />
        ) : (
          <CandidatureDetailsForm
            key={activeTab}
            candidature={activeTabData?.content as ICandidature}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(force) => handleCancel(activeTab, force)}
            onEdit={handleEdit}
            tableHead={tableHead}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        )
      )}

      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
      <UnsavedChangesDialog
        open={showFormulaireConfirmDialog}
        onClose={() => setFormulaireShowConfirmDialog(false)}
        onConfirm={() => handleFormulaireConfirmDialogAction()}
        onCancel={() => setFormulaireShowConfirmDialog(false)}
      />
    </Box>
  );
} 