import { ICandidature, CandidatureStatut } from '@/shared/types/candidature';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { 
  _candidatures, 
  DEFAULT_CANDIDATURE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_RETENUS_TABLE_HEAD,
  DEFAULT_CANDIDATURE_RETENUS_CHAUFFEUR_TABLE_HEAD,
  DEFAULT_CANDIDATURE_RETENUS_SEDENTAIRE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_RDV_SEMAINE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_RDV_SEMAINE_CHAUFFEUR_TABLE_HEAD,
  DEFAULT_CANDIDATURE_RDV_SEMAINE_SEDENTAIRE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_ABSENT_RDV_TABLE_HEAD,
  DEFAULT_CANDIDATURE_ABSENT_RDV_CHAUFFEUR_TABLE_HEAD,
  DEFAULT_CANDIDATURE_ABSENT_RDV_SEDENTAIRE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_TABLEAU_TABLE_HEAD,
  DEFAULT_CANDIDATURE_TABLEAU_CHAUFFEUR_TABLE_HEAD,
  DEFAULT_CANDIDATURE_TABLEAU_SEDENTAIRE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_TOUS_TABLE_HEAD,
  DEFAULT_CANDIDATURE_TOUS_SEDENTAIRE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_REFUSES_BLACKLISTES_TABLE_HEAD,
  DEFAULT_CANDIDATURE_REFUSES_BLACKLISTES_SEDENTAIRE_TABLE_HEAD,
  DEFAULT_CANDIDATURE_SEDENTAIRE_TABLE_HEAD
} from '@/shared/_mock/_candidature';
import { CandidatureTab } from '@/shared/types/candidature';
import { useMemo, useCallback, useEffect } from 'react';

interface CandidatureTableConfig extends TableConfig<ICandidature> {
  activeTab: CandidatureTab;
}

export function useCandidatureTable(activeTab: CandidatureTab, defaultType?: 'Candidature chauffeur' | 'Candidature sédentaire') {
  const getTableHead = useMemo(() => {
    // First check for specific candidate type for À traiter tab
    if (activeTab === CandidatureTab.ATraiter && defaultType === 'Candidature sédentaire') {
      return DEFAULT_CANDIDATURE_SEDENTAIRE_TABLE_HEAD;
    }
    
    // Then check for tab-specific tableHeads
    switch (activeTab) {
      case CandidatureTab.ATraiter:
        return DEFAULT_CANDIDATURE_TABLE_HEAD;
      case CandidatureTab.Retenus:
        // For Retenus tab, select table head based on candidate type
        if (defaultType === 'Candidature sédentaire') {
          return DEFAULT_CANDIDATURE_RETENUS_SEDENTAIRE_TABLE_HEAD;
        } else {
          return DEFAULT_CANDIDATURE_RETENUS_CHAUFFEUR_TABLE_HEAD;
        }
      case CandidatureTab.RdvSemaine:
        // For RDV Semaine tab, select table head based on candidate type
        if (defaultType === 'Candidature sédentaire') {
          return DEFAULT_CANDIDATURE_RDV_SEMAINE_SEDENTAIRE_TABLE_HEAD;
        } else {
          return DEFAULT_CANDIDATURE_RDV_SEMAINE_CHAUFFEUR_TABLE_HEAD;
        }
      case CandidatureTab.AbsentRdv:
        // For Absent RDV tab, select table head based on candidate type
        if (defaultType === 'Candidature sédentaire') {
          return DEFAULT_CANDIDATURE_ABSENT_RDV_SEDENTAIRE_TABLE_HEAD;
        } else {
          return DEFAULT_CANDIDATURE_ABSENT_RDV_CHAUFFEUR_TABLE_HEAD;
        }
      case CandidatureTab.Tableau:
        // For Tableau tab, select table head based on candidate type
        if (defaultType === 'Candidature sédentaire') {
          return DEFAULT_CANDIDATURE_TABLEAU_SEDENTAIRE_TABLE_HEAD;
        } else {
          return DEFAULT_CANDIDATURE_TABLEAU_CHAUFFEUR_TABLE_HEAD;
        }
      case CandidatureTab.Tous:
        if (defaultType === 'Candidature sédentaire') {
          return DEFAULT_CANDIDATURE_TOUS_SEDENTAIRE_TABLE_HEAD;
        } else {
          return DEFAULT_CANDIDATURE_TOUS_TABLE_HEAD;
        }
      case CandidatureTab.RefusesBlacklistes:
        if (defaultType === 'Candidature sédentaire') {
          return DEFAULT_CANDIDATURE_REFUSES_BLACKLISTES_SEDENTAIRE_TABLE_HEAD;
        } else {
          return DEFAULT_CANDIDATURE_REFUSES_BLACKLISTES_TABLE_HEAD;
        }
      default:
        return DEFAULT_CANDIDATURE_TABLE_HEAD;
    }
  }, [activeTab, defaultType]);

  // Filter data based on active tab and default type
  const filteredInitialData = useMemo(() => {
    // First filter by type if defaultType is provided
    const typeFilteredCandidatures = defaultType 
      ? _candidatures.filter(candidature => 
          candidature.type === defaultType || 
          (defaultType === 'Candidature chauffeur' && !candidature.type))
      : _candidatures;
    
    // Then filter by tab
    switch (activeTab) {
      case CandidatureTab.ATraiter:
        return typeFilteredCandidatures.filter(candidature => candidature.statut === CandidatureStatut.ATraiter);
      case CandidatureTab.Retenus:
        // Show only candidates with status Retenu (not Valide anymore)
        return typeFilteredCandidatures.filter(candidature => 
          candidature.statut === CandidatureStatut.Retenu
        );
      case CandidatureTab.RdvSemaine:
        // Filter for candidates with RDV in the current week
        // Only show candidates with status Retenu (not Valide anymore)
        const today = new Date();
        const startOfWeek = new Date(today);
        startOfWeek.setDate(today.getDate() - today.getDay()); // Start of current week (Sunday)
        const endOfWeek = new Date(today);
        endOfWeek.setDate(startOfWeek.getDate() + 6); // End of current week (Saturday)
        
        return typeFilteredCandidatures.filter(candidature => {
          if (!candidature.dateHeureRdvAgence) return false;
          if (candidature.statut !== CandidatureStatut.Retenu) return false;
          
          const rdvDate = new Date(candidature.dateHeureRdvAgence);
          return rdvDate >= startOfWeek && rdvDate <= endOfWeek;
        });
      case CandidatureTab.AbsentRdv:
        return typeFilteredCandidatures.filter(candidature => candidature.statut === CandidatureStatut.Absent);
      case CandidatureTab.Tableau:
        // For Tableau tab, show only candidates with status Valide
        return typeFilteredCandidatures.filter(candidature => candidature.statut === CandidatureStatut.Valide);
      case CandidatureTab.RefusesBlacklistes:
        // For Refusés et Blacklistés tab, show only candidates with status Refuse or Blackliste
        return typeFilteredCandidatures.filter(candidature => 
          candidature.statut === CandidatureStatut.Refuse || 
          candidature.statut === CandidatureStatut.Blackliste
        );
      case CandidatureTab.Tous:
        // For Tous tab, we show all candidates (historical view)
        return typeFilteredCandidatures;
      case CandidatureTab.Formulaire:
        // For Formulaire tab, we don't need to filter as it shows a different component
        return [];
      default:
        return typeFilteredCandidatures;
    }
  }, [activeTab, defaultType]);

  const candidatureConfig: CandidatureTableConfig = {
    initialData: filteredInitialData,
    defaultTableHead: getTableHead,
    activeTab
  };

  const tableManager = useTableManager<ICandidature>(candidatureConfig);
  
  // Force update tableHead when activeTab changes
  useEffect(() => {
    tableManager.handleResetColumns();
  }, [activeTab, tableManager]);
  
  // Custom handleSave function to update the global _candidatures array
  const handleSave = useCallback((updatedCandidature: ICandidature) => {
    // If defaultType is provided, ensure the candidature has the right type
    if (defaultType && !updatedCandidature.type) {
      updatedCandidature.type = defaultType;
    }
    
    // Update the global _candidatures array
    const index = _candidatures.findIndex(c => c.id === updatedCandidature.id);
    if (index !== -1) {
      _candidatures[index] = updatedCandidature;
    } else {
      _candidatures.push(updatedCandidature);
    }
    
    // Check if the updated candidature should be in the current tab based on its status and type
    let shouldBeInCurrentTab = true;
    
    // First check type filter
    if (defaultType && updatedCandidature.type !== defaultType) {
      shouldBeInCurrentTab = false;
    } else {
      // Then check tab filter
      switch (activeTab) {
        case CandidatureTab.ATraiter:
          shouldBeInCurrentTab = updatedCandidature.statut === CandidatureStatut.ATraiter;
          break;
        case CandidatureTab.Retenus:
          shouldBeInCurrentTab = updatedCandidature.statut === CandidatureStatut.Retenu;
          break;
        case CandidatureTab.AbsentRdv:
          shouldBeInCurrentTab = updatedCandidature.statut === CandidatureStatut.Absent;
          break;
        case CandidatureTab.RdvSemaine:
          if (!updatedCandidature.dateHeureRdvAgence) {
            shouldBeInCurrentTab = false;
          } else if (updatedCandidature.statut !== CandidatureStatut.Retenu) {
            shouldBeInCurrentTab = false;
          } else {
            const today = new Date();
            const startOfWeek = new Date(today);
            startOfWeek.setDate(today.getDate() - today.getDay());
            const endOfWeek = new Date(today);
            endOfWeek.setDate(startOfWeek.getDate() + 6);
            
            const rdvDate = new Date(updatedCandidature.dateHeureRdvAgence);
            shouldBeInCurrentTab = rdvDate >= startOfWeek && rdvDate <= endOfWeek;
          }
          break;
        case CandidatureTab.Tableau:
          shouldBeInCurrentTab = updatedCandidature.statut === CandidatureStatut.Valide;
          break;
        case CandidatureTab.RefusesBlacklistes:
          shouldBeInCurrentTab = 
            updatedCandidature.statut === CandidatureStatut.Refuse || 
            updatedCandidature.statut === CandidatureStatut.Blackliste;
          break;
        case CandidatureTab.Tous:
          // This tab shows all candidates
          shouldBeInCurrentTab = true;
          break;
        default:
          shouldBeInCurrentTab = true;
      }
    }
    
    // Use the original handleSave from tableManager
    if (shouldBeInCurrentTab) {
      tableManager.handleSave(updatedCandidature);
    } else {
      // If the candidature should not be in the current tab, remove it
      tableManager.handleDelete(updatedCandidature.id);
    }
  }, [activeTab, tableManager, defaultType]);

  return {
    ...tableManager,
    handleSave,
  };
} 