/* 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 type { HttpError } from '@/api/ius/types';
import { useFormStore } from '@/store/ius/form';
import { Button } from '@repo/ui';
import { pick } from 'radash';
import { useCallback, useContext } from 'react';

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

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.all(uploadFiles)
      .then(async (res) => {
        const errors = res.filter((x) => typeof x !== 'boolean') as HttpError[];

        if (!errors.length) {
          setFormState({
            status: 'success',
            text: SUCCESS_UPLOAD_DOCUMENTS,
          });

          setTimeout(() => {
            window.location.reload();
          }, 500);

          return;
        }

        const error = errors.find((x) => x.errors.length)?.errors.at(0) || ERROR_UPLOAD_DOCUMENT;

        setFormState({ status: 'error', text: error });
      })
      .catch((error) => {
        setFormState({
          status: 'error',
          text: error ? JSON.stringify(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} disabled={!formFiles.length}>
        Отмена
      </Button>
      <Button onClick={handleUploadFiles} disabled={!formFiles.length}>
        Загрузить файлы
      </Button>
    </div>
  );
}
