import { FC, useCallback, useState } from "react";
import { GoFileZip } from "react-icons/go";
import Button from "@/components/generics/button/Button";
import { useCreateDataset } from "@/api/documents/hooks";
import { CreateDatasetFormProps } from "./CreateDatasetForm.interface";
import "../styles.scss";

export const CreateDatasetForm: FC<CreateDatasetFormProps> = ({ closeModal, setSearchParams }) => {
  const [file, setFile] = useState<File | undefined>();
  const { mutate: createDatasetFn, isPending: isPendingCreate } = useCreateDataset();

  const handleUpload = useCallback(() => {
    if (file) {
      const formData = new FormData();

      formData.append("file", file);
      createDatasetFn(formData, {
        onSuccess: (newDatasetData) => {
          closeModal();
          setSearchParams({ datasetId: newDatasetData.id.toString() });
        },
      });
    }
  }, [closeModal, createDatasetFn, file, setSearchParams]);

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