'use client';

import React, { useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ChevronLeft, ChevronRight, Send, Car, Cpu } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import { toast } from 'sonner';
import { WizardHeader, WizardStepper, PageLoader } from '@/components/teltoinstall/_index';
import { useInstallationWizard } from '@/hooks/teltoinstall/_index';
import { buildHydratePayload } from '@/hooks/teltoinstall/installation/useResumeInstallation';
import { hydrateInstallation, setSaveError } from '@/store/slices/installation-slice';
import { InstallationRepository } from '@/repositories/teltoinstall/_index';
import { WIZARD_FORM_ID } from './constants';
import VehicleStep from './steps/VehicleStep';
import DeviceStep from './steps/DeviceStep';
import WiringStep from './steps/WiringStep';
import ValidationStep from './steps/ValidationStep';
import PhotosStep from './steps/PhotosStep';
import SummaryStep from './steps/SummaryStep';

const STEPS = [VehicleStep, DeviceStep, WiringStep, ValidationStep, PhotosStep, SummaryStep];

const STEP_TITLE_KEYS = ['vehicle', 'device', 'wiring', 'validation', 'photos', 'summary'] as const;

export default function InstallationWizardLayout() {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const router = useRouter();
  const params = useParams();
  const routeId = params?.id ? Number(params.id) : null;
  const { currentStep, totalSteps, nextStep, prevStep, isSaving, saveError, vehicle, device, installationId } =
    useInstallationWizard();

  // Les erreurs de sauvegarde serveur/réseau sont stockées dans le store mais
  // n'avaient aucun rendu : on les remonte en toast puis on nettoie l'état.
  // `saveError` est déjà un message prêt à afficher (message backend ou repli
  // traduit), donc on ne le repasse pas par `t()`.
  useEffect(() => {
    if (!saveError) return;
    toast.error(saveError);
    dispatch(setSaveError(null));
  }, [saveError, dispatch]);

  // Charge la pose désignée par l'URL quand ce n'est pas déjà celle en mémoire
  // (rechargement de page, ou ouverture dans un second onglet). Le serveur est la
  // source de vérité — chaque étape y est déjà sauvegardée. `installationId ===
  // routeId` signifie que la pose vient d'être hydratée avant la navigation
  // (reprise / démarrage), donc on ne refait pas d'appel.
  const needsHydration = routeId != null && installationId !== routeId;
  useEffect(() => {
    if (!needsHydration || routeId == null) return;
    let cancelled = false;
    InstallationRepository.getDetail(routeId)
      .then((detail) => {
        if (!cancelled) dispatch(hydrateInstallation(buildHydratePayload(detail)));
      })
      .catch(() => {
        if (cancelled) return;
        // Pose introuvable (supprimée / ID invalide) : retour à l'historique.
        toast.error(t('wizard.saveError'));
        router.replace('/history');
      });
    return () => {
      cancelled = true;
    };
  }, [needsHydration, routeId, dispatch, router, t]);

  // Brouillon neuf (route `/installation` sans ID) : dès que la pose est créée
  // côté serveur (`initInstallation`), on inscrit son ID dans l'URL. Ainsi un
  // rechargement recharge LA bonne pose, et chaque onglet reste indépendant.
  useEffect(() => {
    if (routeId == null && installationId != null) {
      router.replace(`/installation/${installationId}`, { scroll: false });
    }
  }, [routeId, installationId, router]);

  const StepComponent = STEPS[currentStep];
  const isLastStep = currentStep === totalSteps - 1;
  const titleKey = STEP_TITLE_KEYS[currentStep];

  // Barre de contexte : identifie en permanence la pose éditée (immatriculation +
  // IMEI + ID), pour distinguer plusieurs installations en cours reprises tour à
  // tour — sinon rien à l'écran ne dit sur laquelle on travaille.
  const plate = vehicle?.license_plate?.trim();
  const imei = device?.imei?.trim();

  // Tant que la pose de l'URL n'est pas chargée, on affiche un loader plein écran
  // plutôt qu'un wizard aux champs vides (le temps de la requête serveur).
  if (needsHydration) {
    return (
      <div className="h-screen flex flex-col bg-background">
        <div className="flex-shrink-0">
          <WizardHeader />
        </div>
        <div className="flex-1 flex items-center justify-center">
          <PageLoader />
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen flex flex-col bg-background">
      <div className="flex-shrink-0">
        <WizardHeader />
        <WizardStepper currentStep={currentStep} />
        <div className="bg-primary/5 border-b border-border px-4 py-2 flex items-center gap-3 text-xs">
          <span className="inline-flex items-center gap-1.5 font-mono font-bold text-foreground truncate">
            <Car className="w-3.5 h-3.5 text-primary shrink-0" />
            {plate || t('wizard.contextNew')}
          </span>
          <span className="inline-flex items-center gap-1.5 font-mono text-muted-foreground truncate">
            <Cpu className="w-3.5 h-3.5 shrink-0" />
            {imei || t('wizard.contextNoImei')}
          </span>
          {installationId != null && (
            <span className="ml-auto text-[10px] font-mono text-muted-foreground shrink-0">
              #{installationId}
            </span>
          )}
        </div>
      </div>

      <div className="flex-1 overflow-y-auto">
        <div className="w-full px-4 pt-4 pb-2">
          <h2 className="text-lg font-bold text-foreground leading-tight">
            {t(`wizard.stepTitles.${titleKey}`)}
          </h2>
          <p className="text-sm text-muted-foreground">
            {t('wizard.stepSubtitle', { current: currentStep + 1, total: totalSteps })}
          </p>
        </div>

        <div className="w-full px-4 pb-6">
          <StepComponent onNext={nextStep} />
        </div>
      </div>

      <div className="flex-shrink-0 bg-white border-t border-border px-4 py-3 shadow-lg z-20">
        <div className="flex gap-3 max-w-lg mx-auto">
          {currentStep > 0 && (
            <button
              type="button"
              onClick={prevStep}
              disabled={isSaving}
              className="flex items-center gap-1.5 px-5 py-3.5 rounded-xl border-2 border-border text-foreground font-semibold text-sm active:scale-95 transition-transform bg-white disabled:opacity-60"
            >
              <ChevronLeft className="w-4 h-4" />
              {t('wizard.back')}
            </button>
          )}

          {!isLastStep ? (
            <button
              type="submit"
              form={WIZARD_FORM_ID}
              disabled={isSaving}
              className="btn-primary flex items-center justify-center gap-2 flex-1 disabled:opacity-70"
            >
              {isSaving ? (
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
              ) : (
                <>
                  {t('wizard.next')}
                  <ChevronRight className="w-4 h-4" />
                </>
              )}
            </button>
          ) : (
            <button
              type="submit"
              form={WIZARD_FORM_ID}
              disabled={isSaving}
              className="btn-success flex items-center justify-center gap-2 flex-1 disabled:opacity-70"
            >
              {isSaving ? (
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
              ) : (
                <>
                  <Send className="w-4 h-4" />
                  {t('wizard.validate')}
                </>
              )}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
