import { useState } from "react";

interface FileUploadProps {
  isFileUploaded: boolean;
  setIsFileUploaded: (isFileUploaded: boolean) => void;
}

function FileUpload({ isFileUploaded, setIsFileUploaded }: FileUploadProps) {
  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const onSubmitFile = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const form = e.currentTarget;
    const formData = new FormData(form);
    const file = formData.get("file") as File;

    if (!file) {
      setError("Please choose a file");
      return;
    }

    // if file is not a text or pdf file, set error
    if (!file.name.endsWith(".txt") && !file.name.endsWith(".pdf")) {
      setError("Please choose a text or PDF file");
      return;
    }

    setIsLoading(true);

    try {
      const response = await fetch(form.action, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data.session_id) {
        sessionStorage.setItem("session_id", data.session_id);
      }

      console.log("response", response);
      setIsFileUploaded(true);
    } catch (error) {
      setError("Error uploading file");
      console.error("Error uploading file", error);
    } finally {
      form.reset();
      setIsLoading(false);
    }
  };

  const onChangeFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.currentTarget.form?.requestSubmit();
  };

  return !isFileUploaded ? (
    <>
      {isLoading && (
        <div className="flex flex-col items-center justify-center w-full">
          <p className="text-gray-500 text-center mb-4">Loading...</p>
          <div className="w-40 h-40 border-4 border-gray-300 border-t-blue-500 rounded-full animate-spin"></div>
        </div>
      )}
      {!isLoading && (
        <form
          method="post"
          action="/api/file"
          onSubmit={onSubmitFile}
          encType="multipart/form-data"
          className="w-full"
        >
          {error && <p className="text-red-500 text-center mb-4">{error}</p>}
          <div className="bg-white relative w-full h-40 flex items-center justify-center text-gray-500 rounded-3xl relative border border-transparent hover:border-blue-500 hover:text-blue-500 transition-colors duration-300 shadow-md">
            <input
              type="file"
              name="file"
              onChange={onChangeFile}
              placeholder="Upload a file"
              className="absolute inset-0 opacity-0 cursor-pointer"
            />
            <p className="text-center">
              <span className="font-bold text-xl">Drop a .pdf or .txt</span>
              <br />
              or click to upload
            </p>
          </div>
        </form>
      )}
    </>
  ) : null;
}

export { FileUpload };
