import { FormContext } from './context/form-context';
import * as apiIus from '@/api/ius/query';
import { useFormStore } from '@/store/ius/form';
import { useContext } from 'react';
import { Button } from 'ui';

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

  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="secondary">Возврат на доработку</Button>
      <Button
        onClick={() => {
          apiIus.validate({ createUrl, payload: values }).then((res) => {
            if (typeof res !== 'boolean') {
              Object.keys(res.errors).forEach((name) => {
                const elementValidation = res?.errors?.[name];
                if (elementValidation)
                  setValidation({ message: elementValidation[0] ?? '', name, valid: false });
              });
            }
          });
        }}
      >
        Сохранить
      </Button>
    </div>
  );
}
