import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { encodeCheckoutToken } from "@/lib/checkout";
import { whatsappLink } from "@/lib/site";
import ToolIcon from "@/components/ToolIcon";
import ToolCard from "@/components/ToolCard";
import { Price } from "@/lib/currency";

export const revalidate = 300;

type Props = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const tool = await prisma.tool.findUnique({ where: { slug } });
  if (!tool) return { title: "Tool not found" };
  return {
    title: `${tool.name} Premium Group Buy Access`,
    description: tool.description?.slice(0, 160) ?? tool.features?.slice(0, 160),
  };
}

export default async function ToolDetailPage({ params }: Props) {
  const { slug } = await params;
  const tool = await prisma.tool.findUnique({
    where: { slug },
    include: { category: true },
  });
  if (!tool) notFound();

  const related = await prisma.tool.findMany({
    where: { id: { not: tool.id } },
    include: { category: true },
    orderBy: { sortOrder: "asc" },
    take: 4,
  });

  const features = (tool.features ?? "").split("\n").filter(Boolean);
  const checkoutToken = encodeCheckoutToken({ type: "tool", id: tool.id });

  return (
    <>
      <section className="border-b border-slate-100 bg-gradient-to-b from-brand-50/60 to-white py-16">
        <div className="mx-auto grid max-w-7xl items-center gap-12 px-4 sm:px-6 lg:grid-cols-2 lg:px-8">
          <div>
            {tool.badge && (
              <span className="inline-block rounded-full bg-amber-50 px-4 py-1.5 text-xs font-bold text-amber-600 ring-1 ring-amber-200">
                {tool.badge}
              </span>
            )}
            <div className="mt-4 flex items-center gap-5">
              <ToolIcon name={tool.name} iconUrl={tool.iconUrl} size="lg" />
              <div>
                <h1 className="text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl">
                  {tool.name}
                </h1>
                {tool.category && (
                  <p className="mt-1 text-sm font-semibold text-brand-600">{tool.category.name}</p>
                )}
              </div>
            </div>
            {features.length > 0 && (
              <>
                <p className="mt-7 text-xs font-semibold text-slate-400">✨ Features:</p>
                <ul className="mt-2 space-y-1.5">
                  {features.map((f, i) => (
                    <li key={i} className="text-sm leading-relaxed text-slate-600">
                      {f}
                    </li>
                  ))}
                </ul>
              </>
            )}
            <p className="mt-7 text-3xl font-extrabold text-slate-900">
              <Price bdt={tool.price} />
              <span className="text-sm font-medium text-slate-400"> / {tool.period}ly</span>
            </p>
            <div className="mt-6 flex flex-wrap gap-4">
              <Link
                href={`/checkout/${checkoutToken}/`}
                className="rounded-xl bg-brand-600 px-7 py-3.5 text-sm font-semibold text-white shadow-lg shadow-brand-600/25 transition-colors hover:bg-brand-700"
              >
                Purchase Now
              </Link>
              <a
                href={whatsappLink(`Hi! I have a question about ${tool.name}.`)}
                target="_blank"
                rel="noopener noreferrer"
                className="rounded-xl border border-slate-200 px-7 py-3.5 text-sm font-semibold text-slate-700 transition-colors hover:bg-slate-50"
              >
                Chat with Support
              </a>
            </div>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
              <span className="text-2xl" aria-hidden>💬</span>
              <h3 className="mt-3 font-bold text-slate-900">Live Support</h3>
              <p className="mt-1 text-sm text-slate-500">24/7 Support</p>
            </div>
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
              <span className="text-2xl" aria-hidden>⚡</span>
              <h3 className="mt-3 font-bold text-slate-900">Setup Status</h3>
              <p className="mt-1 text-sm text-slate-500">Instant Access</p>
            </div>
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
              <span className="text-2xl" aria-hidden>🔒</span>
              <h3 className="mt-3 font-bold text-slate-900">Secure Payment</h3>
              <p className="mt-1 text-sm text-slate-500">100% Safe Checkout</p>
            </div>
            <div className="rounded-2xl border border-slate-100 bg-white p-6 shadow-sm">
              <span className="text-2xl" aria-hidden>⭐</span>
              <h3 className="mt-3 font-bold text-slate-900">Rated 4.9/5</h3>
              <p className="mt-1 text-sm text-slate-500">By 15,000+ users</p>
            </div>
          </div>
        </div>
      </section>

      {tool.description && (
        <section className="bg-white py-16">
          <div className="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
            <p className="text-sm font-semibold uppercase tracking-wide text-brand-600">
              Description
            </p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-tight text-slate-900">
              About {tool.name}
            </h2>
            <div className="mt-6 space-y-4">
              {tool.description.split("\n\n").map((para, i) => (
                <p key={i} className="leading-relaxed text-slate-600">
                  {para}
                </p>
              ))}
            </div>
          </div>
        </section>
      )}

      <section className="bg-slate-50/70 py-16">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <p className="text-sm font-semibold uppercase tracking-wide text-brand-600">
              Recommendations
            </p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl">
              Related Tools
            </h2>
            <p className="mx-auto mt-4 max-w-2xl text-slate-500">
              Discover more professional tools that complement your current selection.
            </p>
          </div>
          <div className="mt-12 grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
            {related.map((t) => (
              <ToolCard
                key={t.id}
                tool={{
                  name: t.name,
                  slug: t.slug,
                  price: t.price,
                  period: t.period,
                  iconUrl: t.iconUrl,
                  badge: t.badge,
                  categoryName: t.category?.name ?? null,
                  checkoutToken: encodeCheckoutToken({ type: "tool", id: t.id }),
                }}
              />
            ))}
          </div>
        </div>
      </section>
    </>
  );
}
