"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { ArrowRight, Hammer, Loader2 } from "lucide-react";
import { Breadcrumb, type BreadcrumbItem } from "@/components/ui/breadcrumb";
import { publicApi } from "@/lib/api/client";
import { useTranslation } from "@/lib/hooks/use-translation";
import { PUBLIC_NAV, visibleNav, type PublicNavDesk, type PublicNavItem } from "@/lib/constants/public-nav";
import { usePaymentsEnabled } from "@/lib/hooks/use-payments-enabled";

/** Finds a nav item (desk or child) by href, plus its parent desk if any. */
function findNavItem(href: string): { item: PublicNavItem; parent?: PublicNavDesk } | null {
  for (const desk of PUBLIC_NAV) {
    if (desk.href === href) return { item: desk };
    for (const child of desk.children ?? []) {
      if (child.href === href) return { item: child, parent: desk };
    }
  }
  return null;
}

/** Navy hero band with breadcrumb and bilingual title — shared by all public pages. */
export function PublicPageHeader({
  titleHi,
  titleEn,
  breadcrumbs,
}: {
  titleHi: string;
  titleEn: string;
  breadcrumbs: BreadcrumbItem[];
}) {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";
  return (
    <section className="bg-indigo-800 py-10 text-white">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <Breadcrumb items={breadcrumbs} />
        <h1 className="mt-3 text-2xl font-bold sm:text-3xl">
          {hi ? titleHi : titleEn}
        </h1>
        <p className="mt-1 text-sm text-indigo-200">{hi ? titleEn : titleHi}</p>
      </div>
    </section>
  );
}

/**
 * Placeholder for a public page whose content arrives with the CMS/archive
 * phases. Titles and breadcrumbs come from the shared nav data by href.
 */
export function PublicPlaceholderPage({ href }: { href: string }) {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";
  const found = findNavItem(href);
  if (!found) return null;
  const { item, parent } = found;

  const breadcrumbs: BreadcrumbItem[] = [
    { label: hi ? "होम" : "Home", href: "/" },
    ...(parent ? [{ label: hi ? parent.labelHi : parent.labelEn, href: parent.href }] : []),
    { label: hi ? item.labelHi : item.labelEn },
  ];

  return (
    <div className="min-h-[60vh] bg-gray-50">
      <PublicPageHeader titleHi={item.labelHi} titleEn={item.labelEn} breadcrumbs={breadcrumbs} />
      <div className="mx-auto max-w-3xl px-4 py-14 sm:px-6 lg:px-8">
        <div className="rounded-lg border border-amber-200 bg-amber-50 p-6 text-center">
          <Hammer className="mx-auto mb-3 h-8 w-8 text-amber-500" />
          <p className="font-medium text-amber-800">
            {hi
              ? "यह पृष्ठ shodh.net से स्थानांतरित किया जा रहा है।"
              : "This page is being migrated from shodh.net."}
          </p>
          <p className="mt-1 text-sm text-amber-700">
            {hi
              ? "सामग्री शीघ्र ही यहाँ उपलब्ध होगी। तब तक मूल पृष्ठ shodh.net पर उपलब्ध है।"
              : "Content will appear here soon. Until then, the original page remains available on shodh.net."}
          </p>
        </div>
      </div>
    </div>
  );
}

interface CmsRow {
  groupKey: string;
  fieldKey: string;
  titleHi?: string;
  titleEn?: string;
  valueHi?: string;
  valueEn?: string;
}

/**
 * A public page whose body was seeded from the legacy shodh.net site into the
 * CMS (section → group 'page' → field 'body', field_type 'html'). Admins edit
 * it at /admin/page-content. Legacy bodies are bilingual, so both language
 * values usually carry the same content.
 */
export function CmsHtmlPage({
  href,
  section,
  titleHi,
  titleEn,
  children,
}: {
  href: string;
  section: string;
  titleHi?: string;
  titleEn?: string;
  children?: React.ReactNode;
}) {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";
  const { paymentsEnabled, isLoading: paymentsLoading } = usePaymentsEnabled();

  const found = findNavItem(href);
  const pageTitleHi = titleHi ?? found?.item.labelHi ?? "";
  const pageTitleEn = titleEn ?? found?.item.labelEn ?? "";
  const parent = found?.parent;

  const { data: rows, isLoading } = useQuery({
    queryKey: ["cms-page", section],
    queryFn: async () => (await publicApi.cms(section)).data as CmsRow[],
  });

  // This page is marked requiresPayments in the nav data, so one flag governs
  // both whether it is listed and whether it renders.
  const switchedOff = found?.item.requiresPayments === true && !paymentsEnabled;

  const bodyRow = rows?.find((r) => r.groupKey === "page" && r.fieldKey === "body");
  const body = (hi ? bodyRow?.valueHi : bodyRow?.valueEn) || bodyRow?.valueEn || bodyRow?.valueHi;

  const breadcrumbs: BreadcrumbItem[] = [
    { label: hi ? "होम" : "Home", href: "/" },
    ...(parent ? [{ label: hi ? parent.labelHi : parent.labelEn, href: parent.href }] : []),
    { label: hi ? pageTitleHi : pageTitleEn },
  ];

  return (
    <div className="min-h-[60vh] bg-gray-50">
      <PublicPageHeader titleHi={pageTitleHi} titleEn={pageTitleEn} breadcrumbs={breadcrumbs} />
      <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6 lg:px-8">
        {isLoading || paymentsLoading ? (
          <div className="flex justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-indigo-600" />
          </div>
        ) : switchedOff ? (
          /* The editor has stopped charging. Reached by a search result, an old
             bookmark or a link in a past email — the nav no longer offers it.
             Showing the fee schedule anyway would tell an author to expect a
             charge that no longer exists. */
          <div className="rounded-lg border border-gray-200 bg-white p-8 text-center">
            <p className="font-medium text-gray-800">
              {hi
                ? "इस समय कोई प्रकाशन शुल्क लागू नहीं है।"
                : "No publication fee applies at this time."}
            </p>
            <p className="mt-2 text-sm text-gray-500">
              {hi
                ? "No publication fee applies at this time."
                : "इस समय कोई प्रकाशन शुल्क लागू नहीं है।"}
            </p>
            <Link
              href="/submit"
              className="mt-6 inline-flex items-center gap-2 rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-700"
            >
              {hi ? "शोधपत्र जमा करें" : "Submit your article"}
              <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        ) : body && body.trim() ? (
          <div
            className="prose prose-sm max-w-none rounded-lg border border-gray-200 bg-white p-6 shadow-sm sm:p-8 prose-headings:text-indigo-900 prose-a:text-indigo-700 prose-table:text-sm"
            dangerouslySetInnerHTML={{ __html: body }}
          />
        ) : (
          <div className="rounded-lg border border-amber-200 bg-amber-50 p-6 text-center">
            <Hammer className="mx-auto mb-3 h-8 w-8 text-amber-500" />
            <p className="font-medium text-amber-800">
              {hi
                ? "इस पृष्ठ की सामग्री शीघ्र उपलब्ध होगी।"
                : "Content for this page is coming soon."}
            </p>
          </div>
        )}
        {children}
      </div>
    </div>
  );
}

/** Hub page for a desk: its children rendered as link cards. */
export function DeskHubPage({ href }: { href: string }) {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";
  const { paymentsEnabled } = usePaymentsEnabled();
  // Filtered, so the Author's Desk does not keep offering a card for a fee
  // schedule the journal has switched off.
  const desk = visibleNav(paymentsEnabled).find((d) => d.href === href);
  if (!desk) return null;

  return (
    <div className="min-h-[60vh] bg-gray-50">
      <PublicPageHeader
        titleHi={desk.labelHi}
        titleEn={desk.labelEn}
        breadcrumbs={[
          { label: hi ? "होम" : "Home", href: "/" },
          { label: hi ? desk.labelHi : desk.labelEn },
        ]}
      />
      <div className="mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {(desk.children ?? []).map((child) => (
            <Link
              key={child.href}
              href={child.href}
              className="group flex items-center justify-between rounded-lg border border-gray-200 bg-white p-5 shadow-sm transition-all hover:border-indigo-300 hover:shadow-md"
            >
              <div>
                <p className="font-semibold text-gray-900 group-hover:text-indigo-700">
                  {hi ? child.labelHi : child.labelEn}
                </p>
                <p className="mt-0.5 text-xs text-gray-500">
                  {hi ? child.labelEn : child.labelHi}
                </p>
              </div>
              <ArrowRight className="h-4 w-4 shrink-0 text-gray-300 transition-colors group-hover:text-indigo-500" />
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}
