import Link from "next/link";
import { Check, Crown, Zap, Building2, ArrowRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { STRIPE_PLANS } from "@/lib/stripe";

export const metadata = {
  title: "Tarifs — NextCRM",
  description: "Des plans adaptés à chaque étape de votre croissance. Démarrez gratuitement, passez Pro quand vous êtes prêt.",
};

type PlanKey = "FREE" | "PRO" | "BUSINESS";

const PLAN_UI: Record<PlanKey, {
  icon: React.ElementType;
  iconBg: string;
  iconColor: string;
  border: string;
  badge?: string;
  cta: string;
  ctaClass: string;
  popular?: boolean;
}> = {
  FREE: {
    icon: Zap,
    iconBg: "bg-slate-100 dark:bg-slate-800",
    iconColor: "text-slate-500",
    border: "border-border",
    cta: "Démarrer gratuitement",
    ctaClass: "bg-slate-900 hover:bg-slate-800 text-white dark:bg-slate-100 dark:hover:bg-slate-200 dark:text-slate-900",
  },
  PRO: {
    icon: Crown,
    iconBg: "bg-amber-100 dark:bg-amber-900/40",
    iconColor: "text-amber-500",
    border: "border-amber-300 dark:border-amber-700",
    badge: "Populaire",
    popular: true,
    cta: "Essayer Pro gratuitement",
    ctaClass: "bg-amber-500 hover:bg-amber-600 text-white",
  },
  BUSINESS: {
    icon: Building2,
    iconBg: "bg-blue-100 dark:bg-blue-900/40",
    iconColor: "text-blue-600",
    border: "border-blue-300 dark:border-blue-700",
    badge: "Tout inclus",
    cta: "Contacter l'équipe",
    ctaClass: "bg-blue-600 hover:bg-blue-700 text-white",
  },
};

const FEATURE_COMPARISON = [
  { label: "Factures / mois",     FREE: "10",           PRO: "100",          BUSINESS: "Illimitées" },
  { label: "Dépenses / mois",     FREE: "50",           PRO: "500",          BUSINESS: "Illimitées" },
  { label: "Utilisateurs",        FREE: "1",            PRO: "5",            BUSINESS: "Illimités"  },
  { label: "Comptes bancaires",   FREE: "1",            PRO: "3",            BUSINESS: "Illimités"  },
  { label: "Devis",               FREE: true,           PRO: true,           BUSINESS: true         },
  { label: "Bons de livraison",   FREE: true,           PRO: true,           BUSINESS: true         },
  { label: "Génération PDF",      FREE: false,          PRO: true,           BUSINESS: true         },
  { label: "Envoi email auto",    FREE: false,          PRO: true,           BUSINESS: true         },
  { label: "Assistant IA",        FREE: false,          PRO: true,           BUSINESS: true         },
  { label: "Rapports avancés",    FREE: false,          PRO: true,           BUSINESS: true         },
  { label: "Export Excel / PDF",  FREE: false,          PRO: false,          BUSINESS: true         },
  { label: "Prédictions IA",      FREE: false,          PRO: false,          BUSINESS: true         },
  { label: "API d'accès",         FREE: false,          PRO: false,          BUSINESS: true         },
  { label: "Support prioritaire", FREE: false,          PRO: false,          BUSINESS: true         },
  { label: "Stockage",            FREE: "100 Mo",       PRO: "5 Go",         BUSINESS: "Illimité"   },
];

function CellValue({ val }: { val: boolean | string }) {
  if (typeof val === "boolean") {
    return val
      ? <Check className="h-4 w-4 text-emerald-500 mx-auto" />
      : <span className="text-muted-foreground text-sm">—</span>;
  }
  return <span className="text-sm font-medium">{val}</span>;
}

export default function PricingPage() {
  return (
    <div className="min-h-screen bg-background">
      {/* Nav */}
      <header className="border-b">
        <div className="max-w-6xl mx-auto px-4 h-14 flex items-center justify-between">
          <Link href="/" className="font-bold text-lg tracking-tight">NextCRM</Link>
          <div className="flex items-center gap-3">
            <Button variant="ghost" size="sm" asChild>
              <Link href="/connexion">Se connecter</Link>
            </Button>
            <Button size="sm" asChild>
              <Link href="/inscription">Essai gratuit <ArrowRight className="h-3.5 w-3.5 ml-1" /></Link>
            </Button>
          </div>
        </div>
      </header>

      <main className="max-w-6xl mx-auto px-4 py-16 space-y-20">
        {/* Hero */}
        <div className="text-center space-y-4 max-w-2xl mx-auto">
          <Badge variant="secondary" className="text-xs">14 jours d'essai gratuit · Sans carte bancaire</Badge>
          <h1 className="text-4xl font-extrabold tracking-tight">
            Un plan pour chaque étape
          </h1>
          <p className="text-lg text-muted-foreground">
            Commencez gratuitement et évoluez selon vos besoins. Annulez à tout moment.
          </p>
        </div>

        {/* Plans */}
        <div className="grid gap-6 lg:grid-cols-3">
          {(Object.keys(STRIPE_PLANS) as PlanKey[]).map((key) => {
            const plan = STRIPE_PLANS[key];
            const ui = PLAN_UI[key];
            const Icon = ui.icon;

            return (
              <div key={key} className={cn(
                "relative flex flex-col rounded-2xl border-2 bg-card overflow-hidden",
                ui.border,
                ui.popular && "shadow-xl scale-[1.02]"
              )}>
                {ui.badge && (
                  <div className="absolute top-0 inset-x-0 flex justify-center">
                    <span className={cn(
                      "inline-block px-4 py-1 text-xs font-semibold rounded-b-full",
                      key === "PRO" ? "bg-amber-500 text-white" : "bg-blue-600 text-white"
                    )}>
                      {ui.badge}
                    </span>
                  </div>
                )}

                <div className="px-7 pt-10 pb-6">
                  <div className={cn("h-11 w-11 rounded-xl flex items-center justify-center mb-4", ui.iconBg)}>
                    <Icon className={cn("h-6 w-6", ui.iconColor)} />
                  </div>
                  <h2 className="text-xl font-bold">{plan.name}</h2>
                  <div className="mt-3">
                    {plan.price === 0 ? (
                      <span className="text-4xl font-extrabold">Gratuit</span>
                    ) : (
                      <>
                        <span className="text-4xl font-extrabold">{plan.price} €</span>
                        <span className="text-muted-foreground ml-1 text-sm">/mois</span>
                      </>
                    )}
                  </div>
                  {plan.price > 0 && (
                    <p className="text-xs text-muted-foreground mt-1">
                      {Math.round(plan.price * 12 * 0.85)} € /an avec −15% annuel
                    </p>
                  )}
                </div>

                <div className="px-7 pb-6 flex-1">
                  <ul className="space-y-2.5">
                    {plan.features.map((f, i) => (
                      <li key={i} className="flex items-start gap-2.5 text-sm">
                        <Check className={cn(
                          "h-4 w-4 mt-0.5 shrink-0",
                          key === "FREE" ? "text-slate-500" : key === "PRO" ? "text-amber-500" : "text-blue-600"
                        )} />
                        <span className="text-muted-foreground leading-snug">{f}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                <div className="px-7 pb-7">
                  <Button className={cn("w-full font-semibold gap-2", ui.ctaClass)} asChild>
                    <Link href="/inscription">
                      {ui.cta}
                      <ArrowRight className="h-4 w-4" />
                    </Link>
                  </Button>
                </div>
              </div>
            );
          })}
        </div>

        {/* Tableau comparatif */}
        <div>
          <h2 className="text-2xl font-bold tracking-tight text-center mb-8">Comparaison détaillée</h2>
          <div className="rounded-xl border overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/40">
                  <th className="text-left px-5 py-3 font-semibold">Fonctionnalité</th>
                  {(["FREE", "PRO", "BUSINESS"] as PlanKey[]).map((k) => (
                    <th key={k} className={cn(
                      "text-center px-5 py-3 font-semibold",
                      k === "PRO" && "bg-amber-50 dark:bg-amber-900/10"
                    )}>
                      {STRIPE_PLANS[k].name}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {FEATURE_COMPARISON.map((row, i) => (
                  <tr key={i} className={cn("border-b last:border-0", i % 2 === 0 && "bg-muted/20")}>
                    <td className="px-5 py-2.5 text-muted-foreground">{row.label}</td>
                    <td className="px-5 py-2.5 text-center"><CellValue val={row.FREE} /></td>
                    <td className={cn("px-5 py-2.5 text-center", "bg-amber-50/50 dark:bg-amber-900/5")}>
                      <CellValue val={row.PRO} />
                    </td>
                    <td className="px-5 py-2.5 text-center"><CellValue val={row.BUSINESS} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* FAQ */}
        <div className="max-w-2xl mx-auto space-y-5">
          <h2 className="text-2xl font-bold tracking-tight text-center">Questions fréquentes</h2>
          {[
            {
              q: "L'essai gratuit nécessite-t-il une carte bancaire ?",
              a: "Non. Vous pouvez démarrer et tester NextCRM pendant 14 jours sans renseigner vos coordonnées bancaires.",
            },
            {
              q: "Puis-je changer de plan à tout moment ?",
              a: "Oui, montées et descentes de plan sont disponibles à tout moment depuis votre espace abonnement. La différence est calculée au prorata.",
            },
            {
              q: "Mes données sont-elles conservées si je rétrograde ?",
              a: "Toutes vos données sont conservées. Certaines fonctionnalités avancées peuvent devenir inaccessibles selon le plan.",
            },
            {
              q: "Comment annuler mon abonnement ?",
              a: "Depuis le portail de gestion Stripe accessible dans vos paramètres. L'annulation prend effet à la fin de la période en cours.",
            },
          ].map((item, i) => (
            <div key={i} className="border rounded-xl px-6 py-4 space-y-1.5">
              <p className="font-semibold text-sm">{item.q}</p>
              <p className="text-sm text-muted-foreground">{item.a}</p>
            </div>
          ))}
        </div>

        {/* CTA final */}
        <div className="text-center rounded-2xl bg-primary/5 border border-primary/20 py-14 px-6 space-y-4">
          <h2 className="text-2xl font-extrabold">Prêt à démarrer ?</h2>
          <p className="text-muted-foreground">Rejoignez des centaines d'entreprises qui font confiance à NextCRM.</p>
          <Button size="lg" className="gap-2 font-semibold" asChild>
            <Link href="/inscription">
              Créer un compte gratuit
              <ArrowRight className="h-4 w-4" />
            </Link>
          </Button>
        </div>
      </main>

      <footer className="border-t mt-16 py-8 text-center text-xs text-muted-foreground">
        © {new Date().getFullYear()} NextCRM · Tous droits réservés ·{" "}
        <Link href="/connexion" className="hover:underline">Se connecter</Link>
      </footer>
    </div>
  );
}
