import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { INITIAL_LEAVE_DATA } from '@/shared/_mock/_absences';
import { IDemandeAbsence, LeaveStatus } from '@/shared/types/leave';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';

const congeConfig: TabConfig<IDemandeAbsence> = {
  type: 'demande',
  listTitle: 'Liste des Demandes',
  newItemTitle: 'Nouvelle Demande',
  initialData: INITIAL_LEAVE_DATA,
  getItemCode: (conge: IDemandeAbsence) =>
    `${conge.requestNumber} - ${conge.requestType} (${
      conge.requestType === 'Congé' ? conge.leaveType : conge.absenceType
    })`,
};

export function useAbsenceTabs() {
  const tabManager = useTabsManager<IDemandeAbsence>(congeConfig);
  const { createAbsence, updateAbsence } = useAbsenceStoree();

  const handleSave = async (absence: IDemandeAbsence, file?: File | null) => {
    try {
      let result;
      if (absence.id) {
        result = await updateAbsence(absence.id, absence, file || undefined);
      } else {
        result = await createAbsence(absence, file || undefined);
      }

      // If the operation was successful, close the tab using handleCancel
      if (result && result.success) {
        tabManager.handleCancel(tabManager.activeTab, true);
      } else {
       
      }

      // Return the result from the store directly
      return result;
    } catch (error: any) {
      console.error('Error in handleSave:', error);
      return {
        success: false,
        data: absence,
        message: error.message || 'Erreur lors de la sauvegarde',
      };
    }
  };

  const handleApprove = async (absence: IDemandeAbsence) => {
    const updatedAbsence: IDemandeAbsence = {
      ...absence,
      status: 'Approved' as LeaveStatus,
      processDate: new Date().toISOString(),
      dateTraitement: new Date().toISOString(),
    };

    try {
      const result = await updateAbsence(absence.id, updatedAbsence);
      return result;
    } catch (error) {
      return absence;
    }
  };

  const handleReject = async (absence: IDemandeAbsence) => {
    const updatedAbsence: IDemandeAbsence = {
      ...absence,
      status: 'Rejected' as LeaveStatus,
      processDate: new Date().toISOString(),
      dateTraitement: new Date().toISOString(),
    };

    try {
      const result = await updateAbsence(absence.id, updatedAbsence);
      return result;
    } catch (error) {
      return absence;
    }
  };

  const handleDelete = async (conge: IDemandeAbsence) => {};

  return {
    ...tabManager,
    handleSave,
    handleApprove,
    handleReject,
    handleDelete,
  };
}
