import prisma from "@/lib/prisma";
import Link from "next/link";
import type { Metadata } from "next";

// Help content changes weekly at most — ISR over force-dynamic.
export const revalidate = 3600;

export const metadata: Metadata = {
  title: "Help Center | AdultWorld",
  description:
    "Find answers to common questions about registration, profile setup, messaging, payments, verification, safety, and more.",
  alternates: {
    canonical: "/help",
  },
  openGraph: {
    title: "Help Center | AdultWorld",
    description:
      "Find answers to common questions about registration, profile setup, messaging, payments, verification, safety, and more.",
  },
};

const CATEGORIES = [
  {
    value: "registration",
    label: "Registration",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
      </svg>
    ),
  },
  {
    value: "profile-setup",
    label: "Profile Setup",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
      </svg>
    ),
  },
  {
    value: "messaging",
    label: "Messaging",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
      </svg>
    ),
  },
  {
    value: "payments",
    label: "Payments",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" />
      </svg>
    ),
  },
  {
    value: "verification",
    label: "Verification",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
      </svg>
    ),
  },
  {
    value: "safety",
    label: "Safety",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
      </svg>
    ),
  },
  {
    value: "technical",
    label: "Technical",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      </svg>
    ),
  },
  {
    value: "agency-club",
    label: "Agency / Club",
    icon: (
      <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
      </svg>
    ),
  },
];

type Props = {
  searchParams: Promise<{ q?: string }>;
};

export default async function HelpCenterPage({ searchParams }: Props) {
  const { q } = await searchParams;

  // Category counts
  const categoryCounts = await prisma.helpArticle.groupBy({
    by: ["category"],
    where: { published: true },
    _count: { id: true },
  });
  const countMap = Object.fromEntries(
    categoryCounts.map((c) => [c.category, c._count.id])
  );

  // Search results
  let searchResults: { id: number; title: string; slug: string; excerpt: string | null; category: string }[] = [];
  if (q && q.trim()) {
    searchResults = await prisma.helpArticle.findMany({
      where: {
        published: true,
        OR: [
          { title: { contains: q } },
          { content: { contains: q } },
        ],
      },
      select: { id: true, title: true, slug: true, excerpt: true, category: true },
      orderBy: { views: "desc" },
      take: 20,
    });
  }

  // Popular articles
  const popularArticles = await prisma.helpArticle.findMany({
    where: { published: true },
    orderBy: { views: "desc" },
    take: 10,
    select: { id: true, title: true, slug: true, category: true, views: true },
  });

  // Recently updated
  const recentArticles = await prisma.helpArticle.findMany({
    where: { published: true },
    orderBy: { updated_at: "desc" },
    take: 5,
    select: { id: true, title: true, slug: true, category: true, updated_at: true },
  });

  function categoryLabel(value: string) {
    return value.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
  }

  return (
    <div className="max-w-5xl mx-auto space-y-10">
      {/* Header */}
      <div className="text-center">
        <h1 className="text-3xl md:text-4xl font-bold mb-3">Help Center</h1>
        <p className="text-text-muted text-lg">
          How can we help you today?
        </p>
      </div>

      {/* Search */}
      <form className="max-w-2xl mx-auto">
        <div className="relative">
          <svg
            className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-text-muted"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="search"
            name="q"
            defaultValue={q ?? ""}
            placeholder="Search help articles..."
            className="w-full bg-surface border border-surface-light rounded-lg pl-12 pr-4 py-3 text-text placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
          />
        </div>
      </form>

      {/* Search Results */}
      {q && q.trim() && (
        <section>
          <h2 className="text-xl font-bold mb-4">
            Search results for &quot;{q}&quot;
            <span className="text-text-muted font-normal text-base ml-2">
              ({searchResults.length} found)
            </span>
          </h2>
          {searchResults.length === 0 ? (
            <div className="bg-surface rounded-lg p-8 text-center">
              <p className="text-text-muted">No articles found matching your search.</p>
            </div>
          ) : (
            <div className="space-y-3">
              {searchResults.map((article) => (
                <Link
                  key={article.id}
                  href={`/help/${article.slug}`}
                  className="block bg-surface rounded-lg p-4 hover:ring-1 hover:ring-primary transition-all"
                >
                  <h3 className="font-semibold hover:text-primary transition-colors">
                    {article.title}
                  </h3>
                  {article.excerpt && (
                    <p className="text-text-muted text-sm mt-1 line-clamp-2">
                      {article.excerpt}
                    </p>
                  )}
                  <span className="inline-block mt-2 text-xs bg-surface-light text-text-muted px-2 py-0.5 rounded">
                    {categoryLabel(article.category)}
                  </span>
                </Link>
              ))}
            </div>
          )}
        </section>
      )}

      {/* Category Grid */}
      {!q && (
        <>
          <section>
            <h2 className="text-xl font-bold mb-4">Browse by Category</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {CATEGORIES.map((cat) => (
                <Link
                  key={cat.value}
                  href={`/help/category/${cat.value}`}
                  className="bg-surface rounded-lg p-5 hover:ring-1 hover:ring-primary transition-all group text-center"
                >
                  <div className="text-primary mb-3 flex justify-center group-hover:scale-110 transition-transform">
                    {cat.icon}
                  </div>
                  <h3 className="font-semibold text-sm group-hover:text-primary transition-colors">
                    {cat.label}
                  </h3>
                  <p className="text-text-muted text-xs mt-1">
                    {countMap[cat.value] ?? 0} articles
                  </p>
                </Link>
              ))}
            </div>
          </section>

          {/* Popular Articles */}
          {popularArticles.length > 0 && (
            <section>
              <h2 className="text-xl font-bold mb-4">Popular Articles</h2>
              <div className="bg-surface rounded-lg divide-y divide-surface-light">
                {popularArticles.map((article) => (
                  <Link
                    key={article.id}
                    href={`/help/${article.slug}`}
                    className="flex items-center justify-between p-4 hover:bg-surface-light/50 transition-colors"
                  >
                    <div className="min-w-0 flex-1">
                      <h3 className="font-medium text-sm truncate hover:text-primary transition-colors">
                        {article.title}
                      </h3>
                      <span className="text-xs text-text-muted">
                        {categoryLabel(article.category)}
                      </span>
                    </div>
                    <span className="text-xs text-text-muted ml-4 shrink-0">
                      {article.views.toLocaleString()} views
                    </span>
                  </Link>
                ))}
              </div>
            </section>
          )}

          {/* Recently Updated */}
          {recentArticles.length > 0 && (
            <section>
              <h2 className="text-xl font-bold mb-4">Recently Updated</h2>
              <div className="bg-surface rounded-lg divide-y divide-surface-light">
                {recentArticles.map((article) => (
                  <Link
                    key={article.id}
                    href={`/help/${article.slug}`}
                    className="flex items-center justify-between p-4 hover:bg-surface-light/50 transition-colors"
                  >
                    <div className="min-w-0 flex-1">
                      <h3 className="font-medium text-sm truncate hover:text-primary transition-colors">
                        {article.title}
                      </h3>
                      <span className="text-xs text-text-muted">
                        {categoryLabel(article.category)}
                      </span>
                    </div>
                    <span className="text-xs text-text-muted ml-4 shrink-0">
                      {new Date(article.updated_at).toLocaleDateString(undefined, {
                        day: "numeric",
                        month: "short",
                        year: "numeric",
                      })}
                    </span>
                  </Link>
                ))}
              </div>
            </section>
          )}
        </>
      )}

      {/* Safety Resources Link */}
      <div className="bg-gold/10 border border-gold/30 rounded-lg p-4 mt-8 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <svg className="w-6 h-6 text-gold" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
          <div>
            <p className="text-text font-semibold text-sm">Safety Resources</p>
            <p className="text-text-muted text-xs">Screening tips, emergency contacts, and reporting guides</p>
          </div>
        </div>
        <Link href="/safety" className="text-gold hover:text-gold/80 text-sm font-medium transition-colors">
          View &rarr;
        </Link>
      </div>
    </div>
  );
}
