"use client";

import { useQuery } from "@tanstack/react-query";
import { Download, ExternalLink, Loader2, Newspaper } from "lucide-react";
import { PublicPageHeader } from "@/components/shared/public-page";
import { useTranslation } from "@/lib/hooks/use-translation";
import { newsApi } from "@/lib/api/client";

interface NewsItem {
  id: string;
  titleHi: string;
  titleEn?: string;
  bodyHi?: string;
  bodyEn?: string;
  postedOn: string;
  linkUrl?: string;
  hasDocumentEn: boolean;
  documentEnName?: string;
  documentEnSize?: number;
  hasDocumentHi: boolean;
  documentHiName?: string;
  documentHiSize?: number;
}

const MONTHS_HI = ["जनवरी","फ़रवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर"];

/** "1 सितम्बर, 2026" / "1 September, 2026" — the journal's own date form. */
function noticeDate(iso: string, hi: boolean): string {
  const [y, m, d] = iso.split("-").map(Number);
  if (!y || !m || !d) return iso;
  if (hi) return `${d} ${MONTHS_HI[m - 1]}, ${y}`;
  const month = new Date(Date.UTC(y, m - 1, d)).toLocaleString("en-GB", { month: "long", timeZone: "UTC" });
  return `${d} ${month}, ${y}`;
}

function fileSize(bytes?: number): string {
  if (!bytes) return "";
  const mb = bytes / (1024 * 1024);
  return mb >= 1 ? `${mb.toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}

function DocumentLink({ href, label, name, size }: { href: string; label: string; name?: string; size?: number }) {
  return (
    <a
      href={href}
      className="inline-flex items-center gap-1.5 rounded-md border border-indigo-200 bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 transition-colors hover:bg-indigo-100"
      title={name}
    >
      <Download className="h-3.5 w-3.5" />
      {label}
      {size ? <span className="font-normal text-indigo-500">({fileSize(size)})</span> : null}
    </a>
  );
}

export default function NewsPage() {
  const { language } = useTranslation("COMMON");
  const hi = language === "hi";

  const { data: items = [], isLoading } = useQuery<NewsItem[]>({
    queryKey: ["public-news"],
    queryFn: async () => {
      const res = await newsApi.list();
      return res.data ?? [];
    },
  });

  return (
    <div className="min-h-[60vh] bg-gray-50">
      <PublicPageHeader
        titleHi="समाचार"
        titleEn="News"
        breadcrumbs={[
          { label: hi ? "होम" : "Home", href: "/" },
          { label: hi ? "सूचना डेस्क" : "Information Desk", href: "/information" },
          { label: hi ? "समाचार" : "News" },
        ]}
      />

      <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6 lg:px-8">
        {isLoading ? (
          <div className="flex items-center justify-center gap-2 py-16">
            <Loader2 className="h-5 w-5 animate-spin text-indigo-500" />
            <span className="text-sm text-gray-400">{hi ? "लोड हो रहा है..." : "Loading…"}</span>
          </div>
        ) : items.length === 0 ? (
          <div className="rounded-lg border border-gray-200 bg-white p-10 text-center">
            <Newspaper className="mx-auto mb-3 h-8 w-8 text-gray-300" />
            <p className="font-medium text-gray-700">
              {hi ? "अभी कोई सूचना नहीं है।" : "There are no notices at the moment."}
            </p>
            <p className="mt-1 text-sm text-gray-400">
              {hi
                ? "नई सूचनाएँ यहाँ प्रकाशित की जाएँगी।"
                : "New notices will be published here."}
            </p>
          </div>
        ) : (
          <ol className="space-y-4">
            {items.map((item) => {
              const title = hi ? item.titleHi : item.titleEn || item.titleHi;
              const body = hi ? item.bodyHi : item.bodyEn || item.bodyHi;
              return (
                <li
                  key={item.id}
                  className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm sm:p-6"
                >
                  <p className="text-xs font-medium uppercase tracking-wide text-indigo-600">
                    {noticeDate(item.postedOn, hi)}
                  </p>
                  <h2 className="mt-1 text-base font-semibold leading-snug text-gray-900">{title}</h2>
                  {body && (
                    <p className="mt-2 whitespace-pre-line text-sm leading-relaxed text-gray-600">{body}</p>
                  )}

                  {(item.hasDocumentEn || item.hasDocumentHi || item.linkUrl) && (
                    <div className="mt-4 flex flex-wrap items-center gap-2">
                      {item.hasDocumentEn && (
                        <DocumentLink
                          href={newsApi.documentUrl(item.id, "en")}
                          label={hi ? "अंग्रेज़ी प्रति" : "English copy"}
                          name={item.documentEnName}
                          size={item.documentEnSize}
                        />
                      )}
                      {item.hasDocumentHi && (
                        <DocumentLink
                          href={newsApi.documentUrl(item.id, "hi")}
                          label={hi ? "हिन्दी प्रति" : "Hindi copy"}
                          name={item.documentHiName}
                          size={item.documentHiSize}
                        />
                      )}
                      {item.linkUrl && (
                        <a
                          href={item.linkUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1.5 text-xs font-medium text-indigo-700 hover:text-indigo-900 hover:underline"
                        >
                          <ExternalLink className="h-3.5 w-3.5" />
                          {hi ? "और जानकारी" : "More information"}
                        </a>
                      )}
                    </div>
                  )}
                </li>
              );
            })}
          </ol>
        )}
      </div>
    </div>
  );
}
