"use client";
import Link from "next/link";
import { useMemo, useState } from "react";
import { Check, Minus } from "lucide-react";
import { Icon } from "../Icon";
import { money } from "@/lib/format";

type Plan = { id: number; name: string; blurb: string; price: number; year_price: number | null; period: string; features: string[]; limits: Record<string, string>; popular: number };
type Prod = { id: number; slug: string; name: string; icon: string; color: string; tagline: string; plans: Plan[] };

export function Compare({ products }: { products: Prod[] }) {
  const [billing, setBilling] = useState<"month" | "year">("month");
  const [sel, setSel] = useState(products[0]?.id);
  const prod = products.find((p) => p.id === sel) || products[0];
  const price = (p: Plan) => (!p.price ? "Custom" : p.period === "once" ? money(p.price) : billing === "year" && p.year_price ? money(Math.round(p.year_price / 12)) : money(p.price));
  const unit = (p: Plan) => (!p.price ? "" : p.period === "once" ? "one-time" : "/mo" + (billing === "year" && p.year_price ? " · billed yearly" : ""));
  const feats = useMemo(() => Array.from(new Set(prod?.plans.flatMap((p) => p.features) || [])), [prod]);
  const limitKeys = useMemo(() => Array.from(new Set(prod?.plans.flatMap((p) => Object.keys(p.limits)) || [])), [prod]);
  const tiers = Math.max(0, ...products.map((p) => p.plans.length));
  if (!prod) return <p className="mt-10 text-center text-slate-500">No products in this category yet.</p>;
  const hasMonthly = products.some((p) => p.plans.some((pl) => pl.period === "month" && pl.year_price));
  return (
    <div className="mt-10">
      {hasMonthly && (
        <div className="mx-auto mb-8 flex w-fit items-center gap-1 rounded-full bg-slate-100 p-1 text-sm font-semibold" role="group" aria-label="Billing period">
          <button onClick={() => setBilling("month")} className={`rounded-full px-5 py-1.5 ${billing === "month" ? "bg-white shadow text-brand" : "text-slate-500"}`}>Monthly</button>
          <button onClick={() => setBilling("year")} className={`rounded-full px-5 py-1.5 ${billing === "year" ? "bg-white shadow text-brand" : "text-slate-500"}`}>Yearly <span className="ml-1 text-[10px] text-emerald-600">SAVE ~17%</span></button>
        </div>
      )}

      {/* Group overview — every product in the category, side by side */}
      <div className="card overflow-hidden"><div className="border-b border-slate-100 px-5 py-4"><h2 className="font-bold">Compare the whole category</h2><p className="text-xs text-slate-500">Tap a product to see its full plan breakdown below.</p></div>
        <div className="scroll-x"><table className="tbl min-w-[560px]"><thead><tr><th>Product</th>{Array.from({ length: tiers }).map((_, i) => <th key={i}>{["Entry", "Popular", "Top"][i] || `Tier ${i + 1}`}</th>)}</tr></thead>
          <tbody>{products.map((p) => (
            <tr key={p.id} className={`cursor-pointer ${p.id === prod.id ? "[&>td]:bg-blue-50/60" : ""}`} onClick={() => setSel(p.id)}>
              <td><button className="flex items-center gap-2.5 font-semibold" aria-pressed={p.id === prod.id}><span className="grid h-8 w-8 place-items-center rounded-lg text-white" style={{ background: p.color }}><Icon name={p.icon} size={15} /></span>{p.name}</button></td>
              {Array.from({ length: tiers }).map((_, i) => <td key={i} className="whitespace-nowrap">{p.plans[i] ? <><b>{price(p.plans[i])}</b> <span className="text-[11px] text-slate-400">{p.plans[i].name}</span></> : "—"}</td>)}
            </tr>))}</tbody></table></div></div>

      {/* Selected product */}
      <div className="mt-10 flex flex-wrap items-center justify-between gap-3"><div><h3 className="flex items-center gap-2 text-2xl font-extrabold tracking-tight">{prod.name}</h3><p className="text-sm text-slate-500">{prod.tagline}</p></div>
        <div className="flex gap-1.5 overflow-x-auto">{products.map((p) => <button key={p.id} onClick={() => setSel(p.id)} className={`btn btn-sm ${p.id === prod.id ? "btn-primary" : "btn-ghost"}`}>{p.name}</button>)}</div></div>
      <div className="mt-5 grid items-stretch gap-4 md:grid-cols-3">
        {prod.plans.map((p) => (
          <div key={p.id} className={`relative flex flex-col rounded-[1.75rem] p-6 ${p.popular ? "bg-gradient-to-b from-brand to-blue-900 text-white shadow-2xl md:-translate-y-2" : "card"}`}>
            {p.popular ? <span className="absolute right-4 top-4 rounded-full bg-white/20 px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider">Most popular</span> : null}
            <h4 className="text-lg font-bold">{p.name}</h4><p className={`text-sm ${p.popular ? "text-blue-100" : "text-slate-500"}`}>{p.blurb}</p>
            <div className="mt-4 text-4xl font-extrabold tracking-tight">{price(p)}</div><div className={`text-xs ${p.popular ? "text-blue-200" : "text-slate-400"}`}>{unit(p)}</div>
            <ul className={`mt-5 flex-1 space-y-2 border-t pt-5 text-sm ${p.popular ? "border-white/20" : "border-slate-100"}`}>{p.features.slice(0, 6).map((f) => <li key={f} className="flex items-start gap-2"><Check size={15} className={`mt-0.5 shrink-0 ${p.popular ? "text-cyan-200" : "text-brand"}`} />{f}</li>)}</ul>
            {p.price ? <Link href={`/checkout/${p.id}?billing=${p.period === "once" ? "once" : billing}`} className={`btn mt-6 w-full ${p.popular ? "btn-white" : "btn-ghost"}`}>Get started</Link> : <Link href="/contact" className="btn btn-ghost mt-6 w-full">Contact sales</Link>}
          </div>
        ))}
      </div>

      {/* Full comparison table */}
      <div className="card mt-10 overflow-hidden"><div className="scroll-x"><table className="tbl min-w-[560px]">
        <thead><tr><th className="w-1/3">Compare plans</th>{prod.plans.map((p) => <th key={p.id} className={p.popular ? "!text-brand" : ""}>{p.name}</th>)}</tr></thead>
        <tbody>
          <tr><td className="font-semibold">Price</td>{prod.plans.map((p) => <td key={p.id}><b>{price(p)}</b> <span className="text-[11px] text-slate-400">{unit(p)}</span></td>)}</tr>
          {limitKeys.map((k) => <tr key={k}><td className="text-slate-600">{k}</td>{prod.plans.map((p) => <td key={p.id} className="font-medium">{p.limits[k] ?? "—"}</td>)}</tr>)}
          {feats.map((f) => <tr key={f}><td className="text-slate-600">{f}</td>{prod.plans.map((p) => <td key={p.id}>{p.features.includes(f) ? <Check size={17} className="text-emerald-600" aria-label="Included" /> : <Minus size={16} className="text-slate-300" aria-label="Not included" />}</td>)}</tr>)}
        </tbody></table></div></div>
    </div>
  );
}
