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

export const revalidate = 300;

export const metadata: Metadata = {
  title: "Packages & Plans — Premium Tool Bundles",
  description:
    "Unlock Full Access to 100+ premium tools while saving more with the perfect plan for you.",
};

export default async function PackagesPage() {
  const [plans, faqs, offeredTools, trialPlan] = await Promise.all([
    prisma.plan.findMany({ orderBy: { sortOrder: "asc" } }),
    prisma.faq.findMany({ orderBy: { sortOrder: "asc" } }),
    prisma.tool.findMany({
      where: { isPrivate: false },
      orderBy: { sortOrder: "asc" },
      take: 24,
    }),
    prisma.plan.findFirst({ where: { slug: "1-day-trial-premium-plan" } }),
  ]);

  const toCard = (plan: (typeof plans)[number]) => ({
    name: plan.name,
    price: plan.price,
    period: plan.period,
    features: plan.features.split("\n").filter(Boolean),
    isPopular: plan.isPopular,
    checkoutToken: encodeCheckoutToken({ type: "plan", id: plan.id }),
  });

  const miniCombo = plans.filter((p) => p.group === "mini-combo").map(toCard);
  const professional = plans.filter((p) => p.group === "professional").map(toCard);

  return (
    <>
      <section className="border-b border-slate-100 bg-gradient-to-b from-brand-50/60 to-white py-16">
        <div className="mx-auto max-w-7xl px-4 text-center sm:px-6 lg:px-8">
          <h1 className="text-4xl font-extrabold tracking-tight text-slate-900 sm:text-5xl">
            Choose a plan that&apos;s right for you
          </h1>
          <p className="mx-auto mt-4 max-w-2xl text-slate-500">
            Unlock Full Access to 100+ premium tools while saving more with the perfect plan for
            you.
          </p>
        </div>
      </section>

      <section className="bg-white py-16">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <PlanGroups miniCombo={miniCombo} professional={professional} />
        </div>
      </section>

      {/* Build Your Own Pack */}
      <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">
            <h2 className="text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl">
              Build Your Own Pack
            </h2>
            <p className="mx-auto mt-4 max-w-2xl text-slate-500">
              Create a personalized toolset by choosing exactly what you need from 100+ powerful
              tools.
            </p>
          </div>
          <div className="mx-auto mt-10 max-w-lg rounded-3xl border border-brand-200 bg-white p-8 text-center shadow-lg">
            <h3 className="text-lg font-bold text-slate-900">Custom</h3>
            <p className="mt-3 text-4xl font-extrabold text-slate-900">
              <Price bdt={600} />
              <span className="text-sm font-medium text-slate-400"> / Month</span>
            </p>
            <p className="mt-2 text-sm font-semibold text-brand-600">5 tools</p>
            <a
              href={whatsappLink("Hi! I want to build my own custom pack of 5 tools.")}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-6 inline-block rounded-xl bg-brand-600 px-8 py-3 text-sm font-semibold text-white transition-colors hover:bg-brand-700"
            >
              Build Custom Pack
            </a>
            <p className="mt-4 text-xs text-slate-400">
              Looking for more custom plans?{" "}
              <a
                href={whatsappLink("Hi! I need a custom plan.")}
                target="_blank"
                rel="noopener noreferrer"
                className="font-semibold text-brand-600 hover:underline"
              >
                Contact Us
              </a>
            </p>
          </div>
        </div>
      </section>

      {/* Trial CTA */}
      <section className="bg-white py-16">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="rounded-3xl bg-gradient-to-r from-brand-600 to-indigo-600 px-8 py-12 text-center">
            <h2 className="text-3xl font-extrabold text-white">Still Confused?</h2>
            <p className="mt-3 text-brand-100">Get 1 day trial to explore our services.</p>
            <Link
              href={
                trialPlan
                  ? `/checkout/${encodeCheckoutToken({ type: "plan", id: trialPlan.id })}/`
                  : "/packages/"
              }
              className="mt-6 inline-block rounded-xl bg-white px-8 py-3.5 text-sm font-semibold text-brand-700 shadow-lg transition-transform hover:scale-105"
            >
              Start 1 day trial
            </Link>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="bg-slate-50/70 py-16">
        <div className="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <h2 className="text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl">
              Frequently Asked Questions
            </h2>
            <p className="mx-auto mt-4 max-w-2xl text-slate-500">
              Everything you need to know about the product and billing.
            </p>
          </div>
          <div className="mt-10">
            <FaqAccordion items={faqs.map((f) => ({ question: f.question, answer: f.answer }))} />
          </div>
        </div>
      </section>

      {/* Offered Tools */}
      <section className="bg-white py-16">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <h2 className="text-center text-3xl font-extrabold tracking-tight text-slate-900 sm:text-4xl">
            Offered Tools
          </h2>
          <div className="mt-10 grid grid-cols-2 gap-4 sm:grid-cols-4 lg:grid-cols-6">
            {offeredTools.map((tool) => (
              <Link
                key={tool.id}
                href={`/tools/${tool.slug}/`}
                className="flex flex-col items-center gap-3 rounded-2xl border border-slate-100 bg-white p-5 text-center shadow-sm transition-all hover:-translate-y-1 hover:shadow-md"
              >
                <ToolIcon name={tool.name} iconUrl={tool.iconUrl} size="sm" />
                <span className="line-clamp-1 text-xs font-semibold text-slate-700">
                  {tool.name}
                </span>
              </Link>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}
