'use client';

import { useDispatch } from 'react-redux';
import { useRouter } from 'next/navigation';
import { hydrateInstallation, WizardStep } from '@/store/slices/installation-slice';
import {
  InstallationDetail,
  ProductLine,
  StockOrigin,
  Wiring,
} from '@/models/teltoinstall/_index';

/**
 * Résout l'étape de reprise = la PREMIÈRE étape incomplète, dans l'ordre, pour
 * ne jamais sauter par-dessus une étape non renseignée. On teste séquentiellement
 * et on s'arrête au premier trou : un champ d'une étape ultérieure déjà rempli
 * (ex. `installer_name`/`intervention_date` pré-remplis par une demande confirmée)
 * ne doit PAS faire avancer la reprise tant que les étapes précédentes sont vides.
 * Étapes : 0 véhicule · 1 boîtier · 2 câblage · 3 validation · 4 photos · 5 récap.
 */
function resolveResumeStep(detail: InstallationDetail): WizardStep {
  if (!detail.vehicle?.license_plate) return 0;
  if (!detail.device?.imei) return 1;
  if (!detail.location) return 2;
  if (!detail.installer_name || !detail.intervention_date) return 3;
  return 4; // tout est saisi jusqu'aux photos : on reprend à l'étape photos
}

/**
 * Loads an existing installation back into the wizard so it can be resumed
 * (in progress) or corrected (already validated / GPS error). Maps the
 * detail response — which nests relations as objects — into the wizard's
 * write model (the `*_id` fields the steps edit), then routes to the wizard.
 */
export function useResumeInstallation() {
  const dispatch = useDispatch();
  const router = useRouter();

  function resume(detail: InstallationDetail) {
    dispatch(hydrateInstallation(buildHydratePayload(detail)));
    router.push(`/installation/${detail.id}`);
  }

  return { resume };
}

/**
 * Mappe un `InstallationDetail` (relations imbriquées) vers le modèle d'écriture
 * du wizard (champs `*_id`). Partagé entre la reprise d'une pose existante et le
 * démarrage d'une pose depuis une demande confirmée. Porte aussi les verrous et,
 * pour le boîtier, retombe sur `locked_telematics_box_id` quand la ligne device
 * n'existe pas encore (cas du démarrage depuis demande).
 */
export function buildHydratePayload(detail: InstallationDetail) {
  const wirings: Wiring[] = (detail.wirings ?? [])
    .filter((w) => w.wire)
    .map((w) => ({
      wire_id: w.wire!.id,
      wire_accessory_id: w.wire_accessory?.id,
    }));

  return {
    installationId: detail.id,
    currentStep: resolveResumeStep(detail),
    vehicle: {
      fleet_vehicle_id: detail.vehicle?.fleet_vehicle_id ?? null,
      license_plate: detail.vehicle?.license_plate ?? undefined,
      vin: detail.vehicle?.vin ?? undefined,
      odometer_km: detail.vehicle?.odometer_km ?? undefined,
      hour_meter: detail.vehicle?.hour_meter ?? undefined,
      fuel_level: detail.vehicle?.fuel_level ?? undefined,
    },
    device: {
      stock_origin: (detail.device?.stock_origin as StockOrigin) ?? undefined,
      telematics_box_id: detail.device?.telematics_box_id ?? detail.locked_telematics_box_id ?? null,
      product_line: (detail.device?.product_line as ProductLine) ?? undefined,
      model: detail.device?.model ?? undefined,
      imei: detail.device?.imei ?? undefined,
      has_can_module: detail.device?.has_can_module ?? false,
      can_module_type_id: detail.device?.can_module_type?.id,
      sim_card: detail.device?.sim_card
        ? {
            iccid: detail.device.sim_card.iccid ?? undefined,
            operator: detail.device.sim_card.operator ?? undefined,
            apn: detail.device.sim_card.apn ?? undefined,
          }
        : undefined,
      accessory_ids: detail.accessories?.map((a) => a.id) ?? [],
    },
    wirings,
    location: detail.location ?? '',
    installer_name: detail.installer_name ?? '',
    intervention_date: detail.intervention_date ?? '',
    notes: detail.notes ?? '',
    program_number: detail.program_number ?? '',
    validation: detail.installation_validation ?? {},
    photos: detail.photos ?? [],
    locked: {
      license_plate: detail.locked?.license_plate ?? false,
      vin: detail.locked?.vin ?? false,
      telematics_box_id: detail.locked?.telematics_box_id ?? false,
    },
  };
}
