"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { BookOpen, Loader2, Search } from "lucide-react";
import { archiveApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";
import { PublicPageHeader } from "@/components/shared/public-page";
import { ArticleCard } from "@/components/ui/article-card";
import { Pagination } from "@/components/ui/pagination";
import type { ArchiveArticle, ArchiveIssue } from "@/types";

/**
 * The legacy archive browser: Vol. 1-17 grouped by volume, plus a bilingual
 * article search across the whole corpus.
 */
export default function ArchivePage() {
  const { language } = useTranslation("JOURNALS");
  const hi = language === "hi";

  const [query, setQuery] = useState("");
  const [submitted, setSubmitted] = useState("");
  const [page, setPage] = useState(0);

  const issuesQuery = useQuery({
    queryKey: ["archive-issues"],
    queryFn: async () => (await archiveApi.issues()).data as ArchiveIssue[],
  });

  const searchQuery = useQuery({
    queryKey: ["archive-search", submitted, page],
    queryFn: async () => (await archiveApi.search(submitted, page)).data,
    enabled: submitted.length >= 2,
  });

  const byVolume = useMemo(() => {
    const groups = new Map<number, ArchiveIssue[]>();
    for (const issue of issuesQuery.data ?? []) {
      const list = groups.get(issue.volume) ?? [];
      list.push(issue);
      groups.set(issue.volume, list);
    }
    return [...groups.entries()].sort((a, b) => b[0] - a[0]);
  }, [issuesQuery.data]);

  const onSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(0);
    setSubmitted(query.trim());
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <PublicPageHeader
        titleHi="अंक संग्रह (खंड 1–17)"
        titleEn="Issues Archive (Vol. 1–17)"
        breadcrumbs={[
          { label: hi ? "होम" : "Home", href: "/" },
          { label: hi ? "पत्रिका" : "The Journal", href: "/journal" },
          { label: hi ? "अंक संग्रह" : "Issues Archive" },
        ]}
      />

      <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
        {/* Search */}
        <form onSubmit={onSearch} className="mb-10 flex max-w-2xl gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={
                hi
                  ? "शीर्षक या लेखक खोजें (हिन्दी/English)…"
                  : "Search titles or authors (Hindi/English)…"
              }
              className="w-full rounded-md border border-gray-300 bg-white py-2.5 pl-9 pr-3 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />
          </div>
          <button
            type="submit"
            className="rounded-md bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-700"
          >
            {hi ? "खोजें" : "Search"}
          </button>
        </form>

        {/* Search results */}
        {submitted && (
          <section className="mb-12">
            <h2 className="mb-4 text-lg font-bold text-gray-900">
              {hi ? `"${submitted}" के परिणाम` : `Results for "${submitted}"`}
              {searchQuery.data && (
                <span className="ml-2 text-sm font-normal text-gray-500">
                  ({searchQuery.data.totalElements})
                </span>
              )}
            </h2>
            {searchQuery.isLoading ? (
              <Loader2 className="h-6 w-6 animate-spin text-indigo-600" />
            ) : searchQuery.data?.content?.length ? (
              <>
                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                  {searchQuery.data.content.map((article: ArchiveArticle) => (
                    <ArticleCard
                      key={article.id}
                      article={article}
                      onDownload={() => window.open(archiveApi.downloadUrl(article.id), "_blank")}
                    />
                  ))}
                </div>
                <div className="mt-6">
                  <Pagination
                    page={page}
                    totalPages={searchQuery.data.totalPages ?? 1}
                    onPageChange={setPage}
                  />
                </div>
              </>
            ) : (
              <p className="text-sm text-gray-500">
                {hi ? "कोई परिणाम नहीं मिला।" : "No results found."}
              </p>
            )}
          </section>
        )}

        {/* Volume browser */}
        {issuesQuery.isLoading ? (
          <div className="flex justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
          </div>
        ) : byVolume.length === 0 ? (
          <div className="rounded-lg border border-gray-200 bg-white p-10 text-center text-gray-500">
            {hi
              ? "संग्रह अभी आयात किया जा रहा है — शीघ्र उपलब्ध होगा।"
              : "The archive is being imported — available soon."}
          </div>
        ) : (
          <div className="space-y-6">
            {byVolume.map(([volume, issues]) => (
              <section
                key={volume}
                className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm"
              >
                <h2 className="mb-3 flex items-center gap-2 text-lg font-bold text-gray-900">
                  <BookOpen className="h-5 w-5 text-indigo-600" />
                  {hi ? `खंड ${volume}` : `Volume ${volume}`}
                </h2>
                <div className="flex flex-wrap gap-3">
                  {issues
                    .sort((a, b) => a.issueLabel.localeCompare(b.issueLabel))
                    .map((issue) => (
                      <Link
                        key={issue.id}
                        href={`/journal/archive/${issue.id}`}
                        className="group rounded-md border border-gray-200 px-4 py-3 transition-all hover:border-indigo-400 hover:bg-indigo-50"
                      >
                        <p className="text-sm font-semibold text-gray-900 group-hover:text-indigo-700">
                          {hi ? `अंक ${issue.issueLabel}` : `Issue ${issue.issueLabel}`}
                        </p>
                        <p className="text-xs text-gray-500">
                          {issue.articleCount} {hi ? "फ़ाइलें" : "files"}
                        </p>
                      </Link>
                    ))}
                </div>
              </section>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
