'use client';

import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { hydrateInstallation } from '@/store/slices/installation-slice';
import { InstallationRepository } from '@/repositories/teltoinstall/_index';
import { apiErrorMessage } from '@/utils/teltoinstall/_index';
import type { InstallationDetail } from '@/models/teltoinstall/_index';
import { buildHydratePayload } from './useResumeInstallation';

/** Pose non validée déjà en cours pour le véhicule/boîtier choisi (modal). */
interface PendingExisting {
  installationRequestId: number;
  vehicleId: number;
  detail: InstallationDetail;
}

/**
 * Démarre une pose depuis un véhicule d'une demande confirmée. Si une pose non
 * validée existe déjà pour ce véhicule + boîtier, on ne crée rien : on expose la
 * pose existante via `pending` pour que la vue affiche un modal « continuer la
 * pose en cours / démarrer une nouvelle ». Sinon on crée et on ouvre le wizard.
 */
export function useStartInstallationFromRequest() {
  const dispatch = useDispatch();
  const router = useRouter();
  const { t } = useTranslation();
  const [startingVehicleId, setStartingVehicleId] = useState<number | null>(null);
  const [pending, setPending] = useState<PendingExisting | null>(null);

  // Ouvre le wizard à l'étape 0 (Véhicule) : un démarrage repart du début même
  // si des champs sont déjà pré-remplis (date d'intervention, installateur…).
  function openNew(detail: InstallationDetail) {
    dispatch(hydrateInstallation({ ...buildHydratePayload(detail), currentStep: 0 }));
    router.push(`/installation/${detail.id}`);
  }

  async function start(installationRequestId: number, vehicleId: number) {
    if (startingVehicleId !== null) return;
    setStartingVehicleId(vehicleId);
    try {
      const { existing, installation } = await InstallationRepository.createFromRequest(
        installationRequestId,
        vehicleId
      );
      if (existing) {
        // Pose en cours détectée : on laisse l'installateur choisir via le modal.
        setPending({ installationRequestId, vehicleId, detail: installation });
        setStartingVehicleId(null);
        return;
      }
      openNew(installation);
    } catch (e) {
      toast.error(apiErrorMessage(e, t('wizard.saveError')));
      setStartingVehicleId(null);
    }
  }

  // Reprend la pose existante là où elle s'était arrêtée (étape résolue).
  function continueExisting() {
    if (!pending) return;
    dispatch(hydrateInstallation(buildHydratePayload(pending.detail)));
    const installationId = pending.detail.id;
    setPending(null);
    router.push(`/installation/${installationId}`);
  }

  // Force la création d'une NOUVELLE pose malgré la pose en cours existante.
  async function startNew() {
    if (!pending) return;
    const { installationRequestId, vehicleId } = pending;
    setStartingVehicleId(vehicleId);
    try {
      const { installation } = await InstallationRepository.createFromRequest(
        installationRequestId,
        vehicleId,
        true
      );
      setPending(null);
      openNew(installation);
    } catch (e) {
      toast.error(apiErrorMessage(e, t('wizard.saveError')));
      setStartingVehicleId(null);
    }
  }

  function cancelPending() {
    setPending(null);
  }

  return { start, startingVehicleId, pending, continueExisting, startNew, cancelPending };
}
