/* 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 { pick } from 'radash';
import { useCallback } from 'react';
import { useContext } from 'react';

const ERROR_UPLOAD_DOCUMENT = 'Произошла ошибка при загрузке документов';

export function Buttons() {
  const { resetValidation } = useFormStore();
  const { formFiles, pageUrlParams, setFormFiles, setFormState } = useContext(FormContext);

  const handleUploadFiles = useCallback(() => {
    setFormState({ status: 'pending' });
    resetValidation();
    const uploadFiles = formFiles.map((formFile) => {
      const formData = new FormData();
      formData.append('file', formFile.file);
      const document = pick(formFile, ['documentTypeId']);

      return apiIus.uploadDocument({
        document,
        formData,
        pageUrlParams,
      });
    });

    return Promise.allSettled(uploadFiles).catch(() => {
      setFormState({ status: 'error', text: ERROR_UPLOAD_DOCUMENT });
      throw new Error(ERROR_UPLOAD_DOCUMENT);
    });
  }, [formFiles, pageUrlParams, resetValidation, setFormState]);

  const handleCancel = () => {
    setFormFiles([]);
  };

  return (
    <div className="grid grid-cols-1 gap-2 gap-x-4 md:grid-cols-3">
      <Button intent="outline-danger" onClick={handleCancel}>
        Отмена
      </Button>
      <Button onClick={handleUploadFiles}>Загрузить файлы</Button>
    </div>
  );
}
