"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { Download, Loader2 } from "lucide-react";
import { api, archiveApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";

/**
 * Legacy per-article download resolver: old
 * ?option=com_phocadownload&download={fileId}:… URLs 301 here; the legacy
 * file id resolves to the imported article and the PDF download starts.
 */
export default function LegacyDownloadResolver() {
  const { fileId } = useParams<{ fileId: string }>();
  const router = useRouter();
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";
  const [state, setState] = useState<"resolving" | "started" | "missing">("resolving");

  useEffect(() => {
    if (!fileId) return;
    let cancelled = false;
    (async () => {
      try {
        const res = await api.get(`/public/archive/legacy/${fileId}`);
        if (cancelled) return;
        window.location.href = archiveApi.downloadUrl(res.data);
        setState("started");
      } catch {
        if (!cancelled) setState("missing");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [fileId, router]);

  return (
    <div className="flex min-h-[50vh] flex-col items-center justify-center gap-4 px-4 text-center">
      {state === "resolving" ? (
        <Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
      ) : state === "started" ? (
        <>
          <Download className="h-10 w-10 text-indigo-600" />
          <p className="font-medium text-gray-800">
            {hi ? "डाउनलोड शुरू हो रहा है…" : "Your download is starting…"}
          </p>
        </>
      ) : (
        <p className="font-medium text-gray-800">
          {hi
            ? "यह फ़ाइल संग्रह में नहीं मिली।"
            : "This file was not found in the archive."}
        </p>
      )}
      <Link href="/journal/archive" className="text-sm font-semibold text-indigo-600 hover:text-indigo-700">
        {hi ? "अंक संग्रह देखें →" : "Browse the archive →"}
      </Link>
    </div>
  );
}
