import { useState } from "react";

export default function FileUpload({
  onUploadSuccess,
}: {
  onUploadSuccess: () => void;
}) {
  const [uploading, setUploading] = useState(false);

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_URL}/upload`,
        {
          method: "POST",
          body: formData,
        }
      );

      if (!response.ok) throw new Error("Upload failed");
      onUploadSuccess();
    } catch (error) {
      console.error("Upload error:", error);
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="w-full max-w-md">
      <label className="flex flex-col items-center p-4 border-2 border-dashed rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900">
        <span className="text-sm mb-2">
          {uploading ? "Uploading..." : "Upload PDF"}
        </span>
        <input
          type="file"
          className="hidden"
          accept=".pdf"
          onChange={handleFileUpload}
          disabled={uploading}
        />
      </label>
    </div>
  );
}
