"use client";
import { ChangeEvent, FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
import React from "react";
import "../globals.css";
function UploadFiles() {
const [file, setFile] = useState<File | undefined>();
const [parsedText, setParsedText] = useState<string | undefined>();
const router = useRouter();
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!file) return;
try {
const data = new FormData();
data.append("file", file);
const res = await fetch("/api/upload", {
method: "POST",
body: data,
});
if (res.ok) {
const result = await res.json();
console.log("Parsed Text from API:", result.parsedText);
setParsedText(result.parsedText);
console.log("File uploaded and parsed successfully");
router.push(`/flashcards?parsedText=${encodeURIComponent(result.parsedText)}`);
} else {
const errorResult = await res.json();
console.error("File upload failed:", errorResult.error);
}
} catch (error) {
console.error("Error uploading file:", error);
}
};
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];
if (!selectedFile) return;
// Check if the selected file is a PDF
if (selectedFile.type !== "application/pdf") {
alert("Please upload a PDF file.");
return;
}
setFile(selectedFile);
};
return (
<div className="flex h-screen justify-center items-center background-gradient bg-gradient">
<div className="bg-white/70 backdrop-blur-lg p-8 rounded-lg shadow-lg w-full max-w-md">
<h1 className="text-4xl text-center mb-6 text-gray-800 font-bold">Upload a PDF file</h1>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="file"
accept="application/pdf"
className="block w-full text-sm text-gray-500
file:mr-4 file:py-2 file:px-4
file:rounded-md file:border-0
file:text-sm file:font-semibold
file:bg-blue-50 file:text-blue-700
hover:file:bg-blue-100"
onChange={handleFileChange}
/>
<button
className="w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded transition-all disabled:opacity-50"
disabled={!file}
>
Upload
</button>
</form>
{file && (
<iframe
src={URL.createObjectURL(file)}
className="w-full h-64 mt-6 rounded border border-gray-300"
title="Uploaded PDF file"
/>
)}
{parsedText && (
<div className="mt-6 text-gray-700">
<h2 className="text-2xl mb-4 font-semibold">Parsed PDF Text:</h2>
<pre className="whitespace-pre-wrap bg-gray-100 p-4 rounded-lg">{parsedText}</pre>
</div>
)}
</div>
</div>
);
}
export default UploadFiles;