import { useAmendmentStore } from '@/shared/api/stores/amendmentStore';
import { useEffect, useState } from 'react';
import { IAvenant } from '@/shared/types/circuit';
import { AmendmentDetailDTO } from '@/shared/types/amendment';

// Map API model to internal model
const mapToIAvenant = (amendmentResponse: AmendmentDetailDTO): IAvenant => {
  const amendment = amendmentResponse.amendment;
  return {
    id: amendment.id,
    dateApplication: amendment.applicationDate,
    etat: amendment.status === 'controle' ? 'controle' : 'non_controle',
    codeCircuit: amendment.circuitCode || '',
    codeAvenant: amendment.amendmentCode,
    intitule: amendment.title,
    objetAvenant: amendment.amendmentPurpose || '',
    type: amendment.type || '',
    dateFin: amendment.endDate || '',
    etablissement: amendment.establishment || '',
    chauffeur: amendment.driver,
    departement: amendment.company,
    clientDO: amendment.clientDO,
    isActive: amendment.active,
    objet: amendment.purpose || '',
  };
};

export function useAvenantDetails(amendmentId?: string) {
  const { getAmendmentById, amendment, trips, schedules, loading, error, getAmendmentTrips, getAmendmentSchedules } = useAmendmentStore();
  const [avenantData, setAvenantData] = useState<IAvenant | null>(null);

  useEffect(() => {
    if (amendmentId) {
      getAmendmentById(amendmentId);
    }
  }, [amendmentId, getAmendmentById]);

  useEffect(() => {
    if (amendmentId) {
      getAmendmentTrips(amendmentId);
      getAmendmentSchedules(amendmentId);
    }
  }, [amendmentId, getAmendmentTrips, getAmendmentSchedules]);

  useEffect(() => {
    if (amendment) {
      setAvenantData(mapToIAvenant(amendment));
    }
  }, [amendment]);

  return {
    avenant: avenantData,
    trips,
    schedules,
    loading,
    error,
  };
}
