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) => {
    try {
      
      let result;
      if (absence.id) {
      
        result = await updateAbsence(absence.id, absence);
      } else {
      
        result = await createAbsence(absence);
      
      }

      // 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) {
      
      // Return a properly structured error response
      return {
        success: false,
        data: absence,
        message:
          error instanceof Error ? error.message : 'Une erreur est survenue 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,
  };
}
