import Link from "next/link";
import Image from "next/image";
import type { Metadata } from "next";
import { SiteHeader } from "@/components/site-header";
import { SiteFooter } from "@/components/site-footer";
import { searchPosts } from "@/lib/cms";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Tìm kiếm | Finzone Network",
  description: "Tìm bài viết về tài chính, crypto, chứng khoán, vàng trên Finzone.",
  robots: { index: false, follow: true },
};

export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; page?: string }>;
}) {
  const sp = await searchParams;
  const q = (sp.q ?? "").trim();
  const page = Math.max(1, parseInt(sp.page ?? "1", 10) || 1);

  let results: Awaited<ReturnType<typeof searchPosts>> | null = null;
  if (q.length >= 2) {
    results = await searchPosts(q, page, 12);
  }

  const totalPages = results ? Math.max(1, Math.ceil(results.totalPages)) : 0;

  return (
    <>
      <SiteHeader />
      <main className="container max-w-4xl mx-auto px-4 py-10 lg:py-14">
        <h1 className="font-display text-3xl lg:text-4xl font-bold mb-6">Tìm kiếm</h1>

        <form method="get" className="flex gap-2 mb-8">
          <input
            type="search"
            name="q"
            defaultValue={q}
            placeholder="Bitcoin, vàng, VN-Index, lãi suất…"
            autoFocus
            className="flex-1 px-4 py-3 rounded-lg bg-bg-elevated border border-stroke-subtle text-base focus:outline-none focus:border-accent-primary"
          />
          <button
            type="submit"
            className="px-5 py-3 rounded-lg bg-accent-primary text-white font-medium hover:bg-accent-primary/90 transition"
          >
            Tìm
          </button>
        </form>

        {!q ? (
          <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-8 text-center text-ink-muted">
            Nhập từ khóa để tìm bài viết.
          </div>
        ) : q.length < 2 ? (
          <div className="rounded-xl border border-amber-500/40 bg-amber-500/10 p-4 text-sm text-amber-300">
            Từ khóa phải có ít nhất 2 ký tự.
          </div>
        ) : !results || results.posts.length === 0 ? (
          <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-8 text-center">
            <div className="text-ink-muted mb-3">Không tìm thấy bài viết nào cho &ldquo;{q}&rdquo;.</div>
            <Link href="/" className="text-accent-primary hover:underline">
              ← Về trang chủ
            </Link>
          </div>
        ) : (
          <>
            <p className="text-sm text-ink-muted mb-5">
              {results.total} kết quả cho &ldquo;<strong className="text-ink-primary">{q}</strong>&rdquo;
              {totalPages > 1 && ` · trang ${page}/${totalPages}`}
            </p>

            <div className="space-y-4">
              {results.posts.map((p) => (
                <Link
                  key={p.id}
                  href={`/${p.slug}`}
                  className="block rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 hover:border-accent-primary transition"
                >
                  <div className="flex gap-4">
                    {p.featured?.url && (
                      <div className="shrink-0 hidden sm:block">
                        <Image
                          src={p.featured.url}
                          alt={p.featured.alt ?? p.title}
                          width={120}
                          height={80}
                          className="rounded-lg object-cover"
                          unoptimized
                        />
                      </div>
                    )}
                    <div className="flex-1 min-w-0">
                      <h2 className="font-display font-semibold text-lg mb-1 line-clamp-2">
                        {p.title}
                      </h2>
                      {p.excerpt && (
                        <p className="text-sm text-ink-secondary line-clamp-2">{p.excerpt}</p>
                      )}
                      <div className="text-xs text-ink-muted mt-2">
                        {p.categories[0]?.name && <>{p.categories[0].name} · </>}
                        {new Intl.DateTimeFormat("vi-VN", {
                          day: "2-digit",
                          month: "2-digit",
                          year: "numeric",
                        }).format(new Date(p.date))}
                      </div>
                    </div>
                  </div>
                </Link>
              ))}
            </div>

            {totalPages > 1 && (
              <div className="flex items-center justify-between mt-8">
                <Link
                  href={page > 1 ? `/tim-kiem?q=${encodeURIComponent(q)}&page=${page - 1}` : "#"}
                  className={`px-4 py-2 rounded-lg border border-stroke-subtle hover:border-accent-primary transition ${
                    page <= 1 ? "pointer-events-none opacity-40" : ""
                  }`}
                >
                  ← Trước
                </Link>
                <span className="text-sm text-ink-muted">
                  {page} / {totalPages}
                </span>
                <Link
                  href={
                    page < totalPages
                      ? `/tim-kiem?q=${encodeURIComponent(q)}&page=${page + 1}`
                      : "#"
                  }
                  className={`px-4 py-2 rounded-lg border border-stroke-subtle hover:border-accent-primary transition ${
                    page >= totalPages ? "pointer-events-none opacity-40" : ""
                  }`}
                >
                  Sau →
                </Link>
              </div>
            )}
          </>
        )}
      </main>
      <SiteFooter />
    </>
  );
}
