"use client";
import { useState } from "react";

export default function Dashboard() {
  const [task, setTask] = useState<string|null>(null);
  const [status, setStatus] = useState("");

  async function upload(file: File) {
    const fd = new FormData();
    fd.append("file", file);
    fd.append("newspaper", "The Hindu");
    fd.append("date", new Date().toISOString().slice(0,10));
    const r = await fetch("/api/upload", {method:"POST", body:fd});
    const j = await r.json();
    setTask(j.task_id);
    poll(j.task_id);
  }

  async function poll(id: string) {
    const r = await fetch(`/api/status/${id}`);
    const j = await r.json();
    setStatus(j.state);
    if (j.state !== "SUCCESS" && j.state !== "FAILURE")
      setTimeout(() => poll(id), 2000);
  }

  return (
    <div className="p-8">
      <h1 className="text-2xl font-bold mb-4">Newspaper Extractor</h1>
      <input type="file" accept="application/pdf"
        onChange={e => e.target.files && upload(e.target.files[0])}
        className="border p-4 rounded" />
      {task && <p className="mt-4">Status: {status}</p>}
    </div>
  );
}
