import { ICandidature, CandidatureTab } from '@/shared/types/candidature';
import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { INITIAL_CANDIDATURE_DATA } from '@/shared/types/candidature';
import { useState, useCallback, useEffect, useMemo } from 'react';

const getListTitleForTab = (tab: CandidatureTab, defaultType?: 'Candidature chauffeur' | 'Candidature sédentaire'): string => {
  let baseTitle = '';
  switch (tab) {
    case CandidatureTab.ATraiter:
      baseTitle = 'Liste des candidatures à traiter';
      break;
    case CandidatureTab.Retenus:
      baseTitle = 'Liste des candidats retenus';
      break;
    case CandidatureTab.RdvSemaine:
      baseTitle = 'Liste des RDV de la semaine';
      break;
    case CandidatureTab.AbsentRdv:
      baseTitle = 'Liste des absents aux RDV';
      break;
    case CandidatureTab.Tableau:
      baseTitle = 'La liste des candidatures validées';
      break;
    case CandidatureTab.Tous:
      baseTitle = 'Liste de toutes les candidatures';
      break;
    case CandidatureTab.RefusesBlacklistes:
      baseTitle = 'Liste des refusés et blacklistés';
      break;
    default:
      baseTitle = 'Liste des candidatures';
  }

  if (defaultType) {
    return `${baseTitle} (${defaultType.replace('Candidature ', '')})`;
  }
  return baseTitle;
};

export function useCandidatureTabs(defaultType?: 'Candidature chauffeur' | 'Candidature sédentaire') {
  const [activeMainTab, setActiveMainTab] = useState<CandidatureTab>(CandidatureTab.ATraiter);
  
  const initialData = useMemo(() => ({ 
    ...INITIAL_CANDIDATURE_DATA,
    ...(defaultType ? { type: defaultType } : {})
  }), [defaultType]);

  const candidatureConfig = useMemo(() => ({
    type: 'candidature',
    listTitle: getListTitleForTab(CandidatureTab.ATraiter, defaultType),
    newItemTitle: defaultType 
      ? `Nouvelle ${defaultType.toLowerCase()}` 
      : 'Nouvelle candidature',
    initialData,
    getItemCode: (candidature: ICandidature) => `${candidature.nom} ${candidature.prenom}`,
  }), [defaultType, initialData]);


  const tabsManager = useTabsManager<ICandidature>(candidatureConfig);
  const { updateListTabTitle } = tabsManager;

  useEffect(() => {
    const newTitle = getListTitleForTab(activeMainTab, defaultType);
    updateListTabTitle(newTitle);
  }, [activeMainTab, updateListTabTitle, defaultType]);

  const handleMainTabChange = useCallback((tab: CandidatureTab) => {
    setActiveMainTab(tab);
    
    if (tabsManager.activeTab !== 'list') {
      tabsManager.handleTabChange({} as React.SyntheticEvent, 'list');
    }
  }, [tabsManager]);

  return {
    ...tabsManager,
    activeMainTab,
    handleMainTabChange,
  };
} 