import "../styles.scss";

import { FC, useCallback, useState } from "react";
import { useAddFileToDataset, useCreateDatasetsDraft } from "@/api/documents/hooks";

import { AddDocumentFormProps } from "./AddDocumentForm.interface";
import Button from "@/components/generics/button/Button";
import { GoFile } from "react-icons/go";

export const AddDocumentForm: FC<AddDocumentFormProps> = ({ datasetId, isDraft, closeModal, setSearchParams }) => {
  const [file, setFile] = useState<File | undefined>();
  const { mutate: addFileToDatasetFn } = useAddFileToDataset();
  const { mutate: createDatasetsDraftFn } = useCreateDatasetsDraft();

  const handleUpload = useCallback(() => {
    if (file) {
      if (!isDraft) {
        createDatasetsDraftFn(datasetId, {
          onSuccess: (newDatasetData) => {
            const formData = new FormData();

            formData.append("file", file);
            addFileToDatasetFn(
              {
                id: newDatasetData.id,
                data: formData,
              },
              {
                onSuccess: () => {
                  closeModal();
                  setSearchParams({ datasetId: newDatasetData.id.toString() });
                },
              }
            );
          },
        });
      } else {
        const formData = new FormData();

        formData.append("file", file);
        addFileToDatasetFn(
          {
            id: datasetId,
            data: formData,
          },
          { onSuccess: closeModal }
        );
      }
    }
  }, [addFileToDatasetFn, closeModal, createDatasetsDraftFn, datasetId, file, isDraft, setSearchParams]);

  return (
    <div>
      <label className="input-file">
        <input type="file" name="file" onChange={(file) => setFile(file.target.files?.[0])} accept=".xml, .docx" />
        <span>Выберите файл формата xml или docx</span>
      </label>
      <div className="file-name">
        {file && <GoFile />}
        {file?.name}
      </div>
      <div className="actions">
        <Button name="Продолжить" onClick={handleUpload} />
      </div>
    </div>
  );
};
