'use client';

import { useDispatch, useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import * as Yup from 'yup';
import { RootState } from '@/store';
import { setInstallerInfo, setSaving, setSaveError } from '@/store/slices/installation-slice';
import { InstallationRepository } from '@/repositories/teltoinstall/_index';
import { apiErrorMessage } from '@/utils/teltoinstall/_index';

export function useValidationStep() {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const { validation, installer_name, intervention_date, installationId, vehicle, device } =
    useSelector((state: RootState) => state.installation);

  const validationSchema = Yup.object({
    installer_name: Yup.string().required(t('errors.installerRequired')),
    intervention_date: Yup.string().required(t('errors.interventionDateRequired')),
  });

  async function saveInstallerInfo(values: { installer_name: string; intervention_date: string }): Promise<boolean> {
    dispatch(setInstallerInfo({ installer_name: values.installer_name, intervention_date: values.intervention_date }));
    if (!installationId) return false;
    dispatch(setSaving(true));
    try {
      await InstallationRepository.update(installationId, {
        installer_name: values.installer_name,
        intervention_date: values.intervention_date,
      });
      return true;
    } catch (err) {
      dispatch(setSaveError(apiErrorMessage(err, t('wizard.saveError'))));
      return false;
    } finally {
      dispatch(setSaving(false));
    }
  }

  return {
    validation,
    installer_name,
    intervention_date,
    validationSchema,
    vehicle,
    device,
    saveInstallerInfo,
  };
}
