
import { useEffect, useState } from "react";
import { differenceInDays } from "date-fns";
import { UseFormWatch } from "react-hook-form";
import { TripFormData } from "@/components/forms/schemas/tripFormSchema";

export function useTripDuration(watch: UseFormWatch<TripFormData>) {
  const [tripDuration, setTripDuration] = useState<number | null>(null);

  // Observer pour le calcul de la durée du voyage
  useEffect(() => {
    const updateDuration = () => {
      const { startDate, endDate } = watch();

      if (startDate && endDate) {
      try {
        const start = new Date(startDate);
        const end = new Date(endDate);

        if (!isNaN(start.getTime()) && !isNaN(end.getTime()) && end >= start) {
          const duration = differenceInDays(end, start) + 1; // +1 car on compte le jour de début et de fin
          setTripDuration(duration);
        } else {
          setTripDuration(null);
        }
      } catch (error) {
        setTripDuration(null);
      }
      } else {
        setTripDuration(null);
      }
    };

    updateDuration();
    const subscription = watch(updateDuration);
    return () => subscription.unsubscribe();
  }, [watch]);

  // Formater la durée du voyage
  const formatTripDuration = (days: number) => {
    if (days === 1) return "1 jour";
    return `${days} jours`;
  };

  return { tripDuration, formatTripDuration };
}
