'use client';

import axios from 'axios';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/store';
import {
  setCurrentStep,
  setInstallationId,
  setSaving,
  setSaveError,
  resetInstallation,
  WizardStep,
} from '@/store/slices/installation-slice';
import { InstallationRepository } from '@/repositories/teltoinstall/_index';

const TOTAL_STEPS = 6;

export function useInstallationWizard() {
  const dispatch = useDispatch();
  const installation = useSelector((state: RootState) => state.installation);

  async function initInstallation() {
    // Reuse a persisted installation only if it still exists server-side. The
    // wizard state lives in localStorage (redux-persist), so a record deleted
    // on the backend (e.g. a DB reset) would otherwise leave the user stuck
    // editing a ghost. On 404 we wipe local state and start fresh; other
    // errors (network/server) are surfaced without discarding progress.
    if (installation.installationId) {
      try {
        await InstallationRepository.getById(installation.installationId);
        return installation.installationId;
      } catch (err) {
        if (axios.isAxiosError(err) && err.response?.status === 404) {
          dispatch(resetInstallation());
        } else {
          dispatch(setSaveError('wizard.saveError'));
          return null;
        }
      }
    }
    dispatch(setSaving(true));
    try {
      const data = await InstallationRepository.create();
      dispatch(setInstallationId(data.id));
      return data.id;
    } catch {
      dispatch(setSaveError('wizard.saveError'));
      return null;
    } finally {
      dispatch(setSaving(false));
    }
  }

  function goToStep(step: WizardStep) {
    dispatch(setCurrentStep(step));
  }

  function nextStep() {
    if (installation.currentStep < TOTAL_STEPS - 1) {
      dispatch(setCurrentStep((installation.currentStep + 1) as WizardStep));
    }
  }

  function prevStep() {
    if (installation.currentStep > 0) {
      dispatch(setCurrentStep((installation.currentStep - 1) as WizardStep));
    }
  }

  return {
    ...installation,
    totalSteps: TOTAL_STEPS,
    initInstallation,
    goToStep,
    nextStep,
    prevStep,
  };
}
