/* eslint-disable react/jsx-curly-newline */
/* eslint-disable no-negated-condition */
import { FormContext } from '../context/form-context';
import * as apiIus from '@/api/ius/query';
import { useFormStore } from '@/store/ius/form';
import { Button } from '@repo/ui';
import { useCallback, useContext } from 'react';

const ERROR_RETRACT = 'Произошла ошибка при возврате на доработку';
const ERROR_SAVE = 'Произошла ошибка при сохранении';

export function Buttons() {
  const { reset, resetValidation, setValidation, status, values } = useFormStore();
  const { pageUrlParams, setFormState } = useContext(FormContext);

  const handleSave = useCallback(() => {
    setFormState({ status: 'pending' });
    resetValidation();
    apiIus.save({ pageUrlParams, payload: values }).then((res) => {
      if (typeof res !== 'boolean') {
        const { errors } = res;

        if (Array.isArray(errors)) {
          setFormState({ status: 'error', text: errors?.at(0) || ERROR_SAVE });

          return;
        }

        Object.keys(errors).forEach((name) => {
          const elementValidation = errors?.[name];
          if (elementValidation)
            setValidation({ message: elementValidation[0] ?? '', name, valid: false });
        });

        setTimeout(() => {
          setFormState({ status: 'edit' });
        }, 300);
      } else {
        setFormState({ status: 'success' });
        setTimeout(() => {
          window.location.reload();
        }, 500);
      }
    });
  }, [pageUrlParams, resetValidation, setFormState, setValidation, values]);

  const handleRetract = useCallback(() => {
    setFormState({ status: 'pending' });
    resetValidation();
    apiIus.retract({ pageUrlParams, payload: values }).then((res) => {
      if (typeof res !== 'boolean') {
        const { errors } = res;

        if (Array.isArray(errors)) {
          setFormState({ status: 'error', text: errors?.at(0) || ERROR_RETRACT });

          return;
        }

        setTimeout(() => {
          setFormState({ status: 'edit' });
        }, 300);
        Object.keys(errors).forEach((name) => {
          const elementValidation = errors?.[name];
          if (elementValidation)
            setValidation({ message: elementValidation[0] ?? '', name, valid: false });
        });
      } else {
        setFormState({ status: 'success' });
        setTimeout(() => {
          window.location.reload();
        }, 500);
      }
    });
  }, [pageUrlParams, resetValidation, setFormState, setValidation, values]);

  return (
    <div className="grid grid-cols-1 gap-2 gap-x-4 md:grid-cols-3">
      <Button
        intent="outline-danger"
        onClick={() => {
          reset();
        }}
      >
        Отмена
      </Button>
      <Button intent="outline-secondary" onClick={handleRetract}>
        Возврат на доработку
      </Button>
      <Button onClick={handleSave} disabled={status !== 'edited'}>
        Сохранить
      </Button>
    </div>
  );
}
