import { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Loader } from "react-feather";

import { request } from "../lib/api";
import { getSessionId, setStoredSessionId } from "../lib/session";
import type { SessionStatus } from "../types/session";

export default function ProcessingPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [message, setMessage] = useState("");

  const sessionId = getSessionId(searchParams.toString());

  useEffect(() => {
    if (!sessionId) {
      setMessage("No active session found. Return to the upload page.");
      return;
    }
    setStoredSessionId(sessionId);

    let active = true;
    const poll = async () => {
      try {
        const status = await request<SessionStatus>(
          `/sessions/${sessionId}/status`,
        );
        if (!active) return;
        if (status?.status === "ready") {
          navigate(`/review-setup?session=${encodeURIComponent(sessionId)}`);
        }
      } catch {
        // keep polling
      }
    };

    poll();
    const timer = setInterval(poll, 2000);
    return () => {
      active = false;
      clearInterval(timer);
    };
  }, [navigate, sessionId]);

  return (
    <main className="max-w-2xl mx-auto my-10 bg-white shadow-sm ring-1 ring-gray-200 rounded-xl p-6 md:p-8">
      <header className="flex items-center gap-4 border-b border-gray-200 pb-4 mb-6">
        <img
          src="/assets/prosento-logo.png"
          alt="Prosento logo"
          className="h-10 w-auto object-contain"
          loading="eager"
        />
        <div>
          <h1 className="text-xl font-semibold text-gray-900">Prosento RepEx</h1>
          <p className="text-sm text-gray-600">Report processing</p>
        </div>
      </header>

      <section className="text-center">
        <div className="mx-auto mb-4 inline-flex h-12 w-12 items-center justify-center rounded-full bg-blue-50 border border-blue-100">
          <Loader className="h-5 w-5 text-blue-700 animate-spin" />
        </div>
        <h2 className="text-2xl font-semibold text-gray-900 mb-2">
          Generating your report
        </h2>
        <p className="text-gray-600 mb-6">
          We are preparing your files and building the final report. This may take a few minutes.
        </p>

        <div className="w-full rounded-full bg-gray-200 h-3 overflow-hidden">
          <div className="h-full bg-blue-600 w-1/2 animate-pulse" />
        </div>

        <p className="text-xs text-gray-500 mt-4">
          You can leave this tab open while we process your submission.
        </p>

        {message ? (
          <p className="text-sm text-red-600 mt-6">{message}</p>
        ) : null}
      </section>
    </main>
  );
}
