import { useState, useCallback } from 'react';
import { StagesApi } from '../api/stages';
import { toast } from 'react-toastify';

export const useStages = (formId) => {
  const [stagesInfo, setStagesInfo] = useState({
    isLoading: false,
    stages: [],
  });
  const [isSaving, setIsSaving] = useState(false);

  const getStages = useCallback(() => {
    if (!formId) return;

    setStagesInfo((prev) => ({ ...prev, isLoading: true }));

    StagesApi.getStages(formId)
      .then((data) => {
        setStagesInfo({
          stages: data.result ?? [],
          isLoading: false,
        });
      })
      .catch((error) => {
        setStagesInfo((prev) => ({ ...prev, isLoading: false }));
        toast.error(
          error?.response?.data?.detail || 'Ошибка при получении этапов',
        );
      });
  }, [formId]);

  const createStage = useCallback(
    (periodStart, periodEnd) => {
      if (!formId) return Promise.reject('Нет formId');

      setIsSaving(true);
      const payload = {
        period_start: periodStart,
        period_end: periodEnd,
      };

      return StagesApi.createStage(formId, payload)
        .then((data) => {
          setStagesInfo((prev) => ({
            ...prev,
            stages: [...prev.stages, ...data.result],
          }));
          toast.success('Этап добавлен');
          return data;
        })
        .catch((error) => {
          toast.error(
            error?.response?.data?.detail || 'Ошибка добавления этапа ',
          );
          throw error;
        })
        .finally(() => {
          setIsSaving(false);
        });
    },
    [formId],
  );

  const updateStage = useCallback(
    (stage) => {
      if (!formId) return Promise.reject('Нет formId');

      setIsSaving(true);

      return StagesApi.updateStage(stage)
        .then((data) => {
          setStagesInfo((prev) => ({
            ...prev,
            stages: prev.stages.map((curStage) =>
              curStage.sheet === stage.sheet &&
              curStage.phase_code === stage.phase_code
                ? data.result
                : curStage,
            ),
          }));
          toast.success('Данные об этапе обновлены');
          return data;
        })
        .catch((error) => {
          toast.error(
            error?.response?.data?.detail || 'Ошибка при обновлении этапа',
          );
          throw error;
        })
        .finally(() => {
          setIsSaving(false);
        });
    },
    [formId],
  );

  const deleteStage = useCallback(
    (stage) => {
      const { sheet, phase_code, budget_form_id } = stage;
      if (!budget_form_id || !sheet || !phase_code) return;

      StagesApi.deleteStage(budget_form_id, sheet, phase_code)
        .then(() => {
          setStagesInfo((prev) => ({
            ...prev,
            stages: prev.stages.filter(
              (curStage) =>
                !(
                  curStage.sheet === sheet &&
                  curStage.phase_code === phase_code
                ),
            ),
          }));
          toast.success('Этап успешно удален');
        })
        .catch((error) => {
          toast.error(
            error?.response?.data?.detail || 'Ошибка при удалении этапа',
          );
        });
    },
    [formId],
  );

  return {
    stagesInfo,
    getStages,
    createStage,
    updateStage,
    deleteStage,
    isSaving,
  };
};
