/* 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 { useRouter } from 'next/navigation';
import { useCallback } from 'react';
import { useContext } from 'react';

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

  const router = useRouter();

  const handleSave = useCallback(() => {
    apiIus.save({ pageUrlParams, payload: values }).then((res) => {
      if (typeof res !== 'boolean') {
        setTimeout(() => {
          setFormState({ status: 'edit' });
        }, 300);
        Object.keys(res.errors).forEach((name) => {
          const elementValidation = res?.errors?.[name];
          if (elementValidation)
            setValidation({ message: elementValidation[0] ?? '', name, valid: false });
        });
      } else {
        setFormState({ status: 'success' });
        setTimeout(() => {
          router.refresh();
        }, 500);
      }
    });
  }, [pageUrlParams, router, setFormState, setValidation, values]);

  const handleRetract = useCallback(() => {
    setFormState({ status: 'pending' });
    resetValidation();
    apiIus.retract({ pageUrlParams, payload: values }).then((res) => {
      if (typeof res !== 'boolean') {
        setTimeout(() => {
          setFormState({ status: 'edit' });
        }, 300);
        Object.keys(res.errors).forEach((name) => {
          const elementValidation = res?.errors?.[name];
          if (elementValidation)
            setValidation({ message: elementValidation[0] ?? '', name, valid: false });
        });
      } else {
        setFormState({ status: 'success' });
        setTimeout(() => {
          router.refresh();
        }, 500);
      }
    });
  }, [pageUrlParams, resetValidation, router, 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}>Сохранить</Button>
    </div>
  );
}
