'use client';

import { Fragment, useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import {
  Check, X, Sparkles, CreditCard, ExternalLink, Zap,
  Users, Brain, Shield, CheckCircle2, Crown, Rocket,
  Star, Building2, Infinity, Bot, Calendar, Target,
  FolderKanban, FileText, Bell, Lock,
} from 'lucide-react';
import { useSubscription } from '@/hooks/use-subscription';
import { PlanBadge } from '@/components/subscription/plan-badge';
import { PLANS, PLAN_ORDER } from '@/lib/subscription/plans';
import type { Plan } from '@/types/subscription';
import { cn } from '@/lib/utils';

/* ─── Per-plan feature bullet points ─────────────────────────────────────── */

interface FeatureBullet {
  icon: React.ComponentType<{ className?: string }>;
  text: string;
  sub?: string;
}

const PLAN_BULLETS: Record<Plan, FeatureBullet[]> = {
  free: [
    { icon: CheckCircle2, text: 'Bis zu 50 Aufgaben', sub: 'Perfekt zum Ausprobieren' },
    { icon: FileText,     text: '20 Notizen speichern' },
    { icon: FolderKanban, text: '3 Projekte verwalten' },
    { icon: Bot,          text: '10 KI-Anfragen / Monat', sub: 'Grundlegender KI-Assistent' },
    { icon: Calendar,     text: 'Kalender & Dashboard' },
  ],
  pro: [
    { icon: Infinity,     text: 'Unbegrenzte Aufgaben', sub: 'Keine Limits, volle Kontrolle' },
    { icon: FileText,     text: 'Unbegrenzte Notizen & Projekte' },
    { icon: Bot,          text: '200 KI-Anfragen / Monat', sub: 'KI-Assistent für den Alltag' },
    { icon: Calendar,     text: 'Vollständiger Kalender' },
    { icon: Target,       text: 'Achievements & Belohnungen' },
  ],
  pro_plus: [
    { icon: Infinity,     text: 'Alles aus Pro, unbegrenzt' },
    { icon: Brain,        text: '1.000 KI-Anfragen / Monat', sub: 'KI-Planung & intelligente Vorschläge' },
    { icon: Sparkles,     text: 'Erweiterte KI-Features', sub: 'Strukturierung, Planung, Vorschläge' },
    { icon: Zap,          text: 'Automationen einrichten', sub: 'Workflows automatisch ausführen' },
    { icon: Crown,        text: 'Volle Achievements & Custom Rewards' },
    { icon: Shield,       text: 'Erweiterte Dashboard-Anpassung' },
  ],
  business: [
    { icon: Infinity,     text: 'Alles aus Pro+, ohne Einschränkungen' },
    { icon: Bot,          text: 'Unbegrenzte KI-Anfragen' },
    { icon: Users,        text: 'Teamverwaltung & Rollen', sub: 'Berechtigungen pro Mitglied' },
    { icon: FolderKanban, text: 'Gemeinsame Projekte & Kalender' },
    { icon: Bell,         text: 'Echtzeit-Zusammenarbeit' },
    { icon: Target,       text: 'Team-Achievements & Leaderboards' },
  ],
  enterprise: [
    { icon: Building2,    text: 'Alles aus Business', sub: 'Für große Organisationen' },
    { icon: Zap,          text: 'Custom Integrationen', sub: 'API, SSO, eigene Systeme' },
    { icon: Lock,         text: 'Erweiterte Sicherheit', sub: 'Compliance & Datenschutz' },
    { icon: Star,         text: 'Persönliches Onboarding' },
    { icon: Shield,       text: 'Dedizierter Priority Support' },
  ],
};

/* ─── Plan visual config ──────────────────────────────────────────────────── */

interface PlanVisual {
  gradient: string;
  border: string;
  accentText: string;
  btnClass: string;
  iconBg: string;
  icon: React.ComponentType<{ className?: string }>;
}

const PLAN_VISUAL: Record<Plan, PlanVisual> = {
  free: {
    gradient: 'bg-white/[0.02]',
    border: 'border-white/[0.08]',
    accentText: 'text-white/60',
    btnClass: 'border border-white/[0.12] bg-white/[0.05] text-white/60 hover:text-white',
    iconBg: 'border-white/[0.10] bg-white/[0.05]',
    icon: Rocket,
  },
  pro: {
    gradient: 'bg-[radial-gradient(ellipse_at_top_left,rgba(14,165,233,0.10),rgba(10,8,18,0.98)_60%)]',
    border: 'border-sky-500/[0.20]',
    accentText: 'text-sky-300',
    btnClass: 'border border-sky-500/[0.25] bg-sky-500/10 text-sky-300 hover:bg-sky-500/20',
    iconBg: 'border-sky-500/[0.20] bg-sky-500/[0.10]',
    icon: Rocket,
  },
  pro_plus: {
    gradient: 'bg-[radial-gradient(ellipse_at_top_left,rgba(139,92,246,0.14),rgba(10,8,18,0.98)_60%)]',
    border: 'border-violet-500/[0.30]',
    accentText: 'text-violet-300',
    btnClass: 'border border-violet-500/[0.30] bg-violet-600/80 text-white hover:bg-violet-600',
    iconBg: 'border-violet-500/[0.25] bg-violet-500/[0.12]',
    icon: Sparkles,
  },
  business: {
    gradient: 'bg-[radial-gradient(ellipse_at_top_left,rgba(245,158,11,0.09),rgba(10,8,18,0.98)_60%)]',
    border: 'border-amber-500/[0.20]',
    accentText: 'text-amber-300',
    btnClass: 'border border-amber-500/[0.25] bg-amber-500/10 text-amber-300 hover:bg-amber-500/20',
    iconBg: 'border-amber-500/[0.20] bg-amber-500/[0.10]',
    icon: Users,
  },
  enterprise: {
    gradient: 'bg-[radial-gradient(ellipse_at_top_left,rgba(16,185,129,0.09),rgba(10,8,18,0.98)_60%)]',
    border: 'border-emerald-500/[0.20]',
    accentText: 'text-emerald-300',
    btnClass: 'border border-emerald-500/[0.25] bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20',
    iconBg: 'border-emerald-500/[0.20] bg-emerald-500/[0.10]',
    icon: Building2,
  },
};

/* ─── Comparison table config ─────────────────────────────────────────────── */

interface CompareRow {
  icon: React.ComponentType<{ className?: string }>;
  category: string;
  label: string;
  sub?: string;
  values: Record<Plan, string | boolean>;
}

const COMPARE_ROWS: CompareRow[] = [
  {
    icon: CheckCircle2,
    category: 'Produktivität',
    label: 'Aufgaben',
    sub: 'Erstelle und verwalte deine Tasks',
    values: { free: '50', pro: '∞', pro_plus: '∞', business: '∞', enterprise: '∞' },
  },
  {
    icon: FileText,
    category: 'Produktivität',
    label: 'Notizen',
    sub: 'Ideen, Gedanken & Wissen festhalten',
    values: { free: '20', pro: '∞', pro_plus: '∞', business: '∞', enterprise: '∞' },
  },
  {
    icon: FolderKanban,
    category: 'Produktivität',
    label: 'Projekte',
    sub: 'Organisiere deine Arbeit in Projekten',
    values: { free: '3', pro: '∞', pro_plus: '∞', business: '∞', enterprise: '∞' },
  },
  {
    icon: Calendar,
    category: 'Produktivität',
    label: 'Kalender',
    sub: 'Vollständiger Kalender & Planung',
    values: { free: 'Basis', pro: 'Voll', pro_plus: 'Voll', business: 'Geteilt', enterprise: 'Geteilt' },
  },
  {
    icon: Bot,
    category: 'KI & Automatisierung',
    label: 'KI-Anfragen / Monat',
    sub: 'Anfragen an deinen KI-Assistenten',
    values: { free: '10', pro: '200', pro_plus: '1.000', business: '∞', enterprise: '∞' },
  },
  {
    icon: Brain,
    category: 'KI & Automatisierung',
    label: 'KI-Planung & Vorschläge',
    sub: 'Intelligente Strukturierung & Empfehlungen',
    values: { free: false, pro: false, pro_plus: true, business: true, enterprise: true },
  },
  {
    icon: Zap,
    category: 'KI & Automatisierung',
    label: 'Automationen',
    sub: 'Workflows automatisch ausführen',
    values: { free: false, pro: false, pro_plus: true, business: true, enterprise: true },
  },
  {
    icon: Target,
    category: 'Motivation',
    label: 'Achievements & Belohnungen',
    sub: 'Gamifiziertes Produktivitätssystem',
    values: { free: false, pro: 'Basis', pro_plus: 'Voll + Custom', business: 'Team-Level', enterprise: 'Team-Level' },
  },
  {
    icon: Users,
    category: 'Team',
    label: 'Teamverwaltung & Rollen',
    sub: 'Mitglieder einladen, Rechte vergeben',
    values: { free: false, pro: false, pro_plus: false, business: true, enterprise: true },
  },
  {
    icon: FolderKanban,
    category: 'Team',
    label: 'Gemeinsame Projekte',
    sub: 'Projekte & Kalender im Team teilen',
    values: { free: false, pro: false, pro_plus: false, business: true, enterprise: true },
  },
  {
    icon: Shield,
    category: 'Support & Sicherheit',
    label: 'Priority Support',
    sub: 'Schnelle Hilfe direkt vom Team',
    values: { free: false, pro: false, pro_plus: false, business: false, enterprise: true },
  },
  {
    icon: Lock,
    category: 'Support & Sicherheit',
    label: 'Custom Integrationen & SSO',
    sub: 'Eigene Systeme, API-Zugang, SSO',
    values: { free: false, pro: false, pro_plus: false, business: false, enterprise: true },
  },
];

/* ─── Cell renderer ──────────────────────────────────────────────────────── */

function CompareCell({ val, isCurrent }: { val: string | boolean; isCurrent: boolean }) {
  if (typeof val === 'boolean') {
    return val
      ? <Check className="w-4 h-4 text-emerald-400 mx-auto" />
      : <X className="w-3.5 h-3.5 text-white/15 mx-auto" />;
  }
  if (val === '∞') {
    return <Infinity className={cn('w-4 h-4 mx-auto', isCurrent ? 'text-violet-300' : 'text-white/50')} />;
  }
  return (
    <span className={cn('text-xs font-semibold tabular-nums', isCurrent ? 'text-white/90' : 'text-white/50')}>
      {val}
    </span>
  );
}

/* ─── Main page ──────────────────────────────────────────────────────────── */

export default function BillingPage() {
  const { subscription, refetch } = useSubscription();
  const searchParams = useSearchParams();
  const [upgrading, setUpgrading] = useState<Plan | null>(null);
  const [portalLoading, setPortalLoading] = useState(false);
  const [banner, setBanner] = useState<'success' | 'canceled' | null>(null);

  const currentPlan: Plan = subscription?.plan ?? 'free';

  useEffect(() => {
    if (searchParams.get('success')) setBanner('success');
    if (searchParams.get('canceled')) setBanner('canceled');
    if (searchParams.get('success') || searchParams.get('canceled')) void refetch();
  }, [searchParams, refetch]);

  async function handleUpgrade(plan: Plan) {
    const priceId = PLANS[plan].stripePriceId;
    if (!priceId) {
      if (plan === 'enterprise') window.location.href = 'mailto:hello@mindavio.app?subject=Enterprise%20Anfrage';
      return;
    }
    setUpgrading(plan);
    try {
      const res = await fetch('/api/stripe/checkout', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ priceId }),
      });
      const { url } = await res.json() as { url?: string };
      if (url) window.location.href = url;
    } finally { setUpgrading(null); }
  }

  async function handlePortal() {
    setPortalLoading(true);
    try {
      const res = await fetch('/api/stripe/portal', { method: 'POST' });
      const { url } = await res.json() as { url?: string };
      if (url) window.location.href = url;
    } finally { setPortalLoading(false); }
  }

  /* ── group compare rows by category ── */
  const categories = [...new Set(COMPARE_ROWS.map(r => r.category))];

  return (
    <div className="min-h-screen bg-background px-4 py-8 text-white md:px-8">
      <div className="mx-auto max-w-6xl space-y-10">

        {/* ── Banners ── */}
        {banner === 'success' && (
          <div className="rounded-2xl border border-emerald-500/[0.20] bg-emerald-500/[0.08] px-5 py-4 flex items-center gap-3">
            <CheckCircle2 className="w-5 h-5 text-emerald-400 flex-shrink-0" />
            <p className="text-sm font-medium text-emerald-200">Upgrade erfolgreich! Dein Plan wurde aktiviert.</p>
            <button onClick={() => setBanner(null)} className="ml-auto text-white/30 hover:text-white/60"><X className="w-4 h-4" /></button>
          </div>
        )}
        {banner === 'canceled' && (
          <div className="rounded-2xl border border-white/[0.08] bg-white/[0.03] px-5 py-4 flex items-center gap-3">
            <X className="w-5 h-5 text-white/40 flex-shrink-0" />
            <p className="text-sm text-white/60">Vorgang abgebrochen.</p>
            <button onClick={() => setBanner(null)} className="ml-auto text-white/30 hover:text-white/60"><X className="w-4 h-4" /></button>
          </div>
        )}

        {/* ── Hero / Current Plan ── */}
        <div className="rounded-[28px] border border-violet-500/[0.14] bg-[radial-gradient(ellipse_at_top_left,rgba(139,92,246,0.09),rgba(10,8,18,0.98)_55%,rgba(9,8,15,1)_100%)] p-8">
          <div className="flex flex-col gap-6 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <p className="text-[10px] font-bold uppercase tracking-[0.18em] text-white/30">Abonnement & Plan</p>
              <h1 className="mt-2 text-[32px] font-black leading-none text-white">
                Dein aktueller Plan
              </h1>
              <div className="mt-4 flex flex-wrap items-center gap-3">
                <PlanBadge plan={currentPlan} />
                {subscription?.status === 'trial' && (
                  <span className="rounded-full border border-amber-500/[0.20] bg-amber-500/[0.08] px-2.5 py-0.5 text-[11px] font-semibold text-amber-300">
                    Trial aktiv
                  </span>
                )}
                {subscription?.current_period_end && currentPlan !== 'free' && (
                  <span className="text-xs text-white/35">
                    Verlängerung: {new Date(subscription.current_period_end).toLocaleDateString('de-DE')}
                  </span>
                )}
              </div>
              <p className="mt-3 max-w-md text-sm text-white/40">
                {currentPlan === 'free'
                  ? 'Du nutzt Mindavio kostenlos. Upgrade jederzeit für mehr Power.'
                  : currentPlan === 'pro'
                  ? 'Pro gibt dir unbegrenzte Aufgaben, Notizen und KI-Unterstützung.'
                  : currentPlan === 'pro_plus'
                  ? 'Mit Pro+ hast du Zugang zu erweiterten KI-Features und Automationen.'
                  : currentPlan === 'business'
                  ? 'Business schaltet alle Team-Features und unbegrenzte KI frei.'
                  : 'Du nutzt Mindavio Enterprise mit individuellem Support.'}
              </p>
            </div>
            {currentPlan !== 'free' && subscription?.stripe_customer_id && (
              <button
                onClick={() => void handlePortal()}
                disabled={portalLoading}
                className="flex shrink-0 items-center gap-2 rounded-2xl border border-white/[0.10] bg-white/[0.04] px-5 py-3 text-sm font-medium text-white/70 hover:text-white transition-colors disabled:opacity-50"
              >
                <CreditCard className="w-4 h-4" />
                {portalLoading ? 'Lädt...' : 'Abrechnung verwalten'}
                <ExternalLink className="w-3.5 h-3.5" />
              </button>
            )}
          </div>
        </div>

        {/* ── Plan cards ── */}
        <div>
          <div className="mb-6 text-center">
            <h2 className="text-2xl font-black text-white">Wähle deinen Plan</h2>
            <p className="mt-1 text-sm text-white/40">Upgrade oder downgrade jederzeit — keine Bindung.</p>
          </div>

          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
            {PLAN_ORDER.map((planId) => {
              const plan = PLANS[planId];
              const visual = PLAN_VISUAL[planId];
              const bullets = PLAN_BULLETS[planId];
              const isCurrentPlan = currentPlan === planId;
              const PlanIcon = visual.icon;

              return (
                <div
                  key={planId}
                  className={cn(
                    'relative flex flex-col rounded-[24px] border p-5 transition-all duration-200',
                    visual.gradient,
                    visual.border,
                    plan.highlighted && 'scale-[1.03] shadow-[0_0_40px_rgba(139,92,246,0.15)]',
                    isCurrentPlan && 'ring-2 ring-violet-500/[0.25]',
                  )}
                >
                  {/* Recommended badge */}
                  {plan.badge && (
                    <div className="absolute -top-3.5 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-full border border-violet-400/[0.35] bg-violet-600 px-3.5 py-1 text-[10px] font-bold tracking-wide text-white shadow-[0_0_16px_rgba(139,92,246,0.4)]">
                      ✦ {plan.badge}
                    </div>
                  )}

                  {/* Current plan indicator */}
                  {isCurrentPlan && (
                    <div className="absolute right-3 top-3 rounded-full border border-violet-500/[0.20] bg-violet-500/10 px-2 py-0.5 text-[9px] font-bold text-violet-300">
                      Aktiv
                    </div>
                  )}

                  {/* Icon + Name */}
                  <div className={cn('mb-4 flex h-9 w-9 items-center justify-center rounded-xl border', visual.iconBg)}>
                    <PlanIcon className={cn('w-4 h-4', visual.accentText)} />
                  </div>

                  <p className={cn('text-[10px] font-bold uppercase tracking-[0.18em]', visual.accentText)}>
                    {plan.name}
                  </p>

                  {/* Price */}
                  <div className="mt-1.5 mb-1">
                    <span className="text-[28px] font-black leading-none text-white">
                      {plan.price === null ? 'Custom' : plan.price === 0 ? 'Kostenlos' : plan.priceLabel}
                    </span>
                    {plan.price !== null && plan.price > 0 && (
                      <span className="ml-1 text-xs text-white/30">/ Monat</span>
                    )}
                  </div>
                  <p className="mb-4 text-xs text-white/40">{plan.description}</p>

                  {/* Feature bullets */}
                  <div className="flex-1 space-y-2.5 mb-5">
                    {bullets.map((b, i) => {
                      const BulletIcon = b.icon;
                      return (
                        <div key={i} className="flex items-start gap-2.5">
                          <div className={cn('mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-md', visual.iconBg)}>
                            <BulletIcon className={cn('w-2.5 h-2.5', visual.accentText)} />
                          </div>
                          <div className="min-w-0">
                            <p className="text-[12px] font-medium leading-tight text-white/80">{b.text}</p>
                            {b.sub && <p className="mt-0.5 text-[10px] text-white/35 leading-tight">{b.sub}</p>}
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  {/* CTA */}
                  {isCurrentPlan ? (
                    <div className="rounded-xl border border-white/[0.08] py-2.5 text-center text-xs font-semibold text-white/35">
                      Aktueller Plan
                    </div>
                  ) : planId === 'enterprise' ? (
                    <button
                      onClick={() => void handleUpgrade(planId)}
                      className={cn('rounded-xl py-2.5 text-xs font-semibold transition-colors', visual.btnClass)}
                    >
                      Kontakt aufnehmen
                    </button>
                  ) : plan.price === 0 ? (
                    <div className="rounded-xl border border-white/[0.05] py-2.5 text-center text-xs text-white/25">
                      Dein Startpunkt
                    </div>
                  ) : (
                    <button
                      disabled={upgrading === planId}
                      onClick={() => void handleUpgrade(planId)}
                      className={cn('rounded-xl py-2.5 text-xs font-semibold transition-colors disabled:opacity-50', visual.btnClass)}
                    >
                      {upgrading === planId ? 'Weiterleitung...' : `Zu ${plan.name} upgraden`}
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* ── Feature comparison ── */}
        <div className="rounded-[28px] border border-white/[0.08] bg-white/[0.01] overflow-hidden">
          <div className="px-8 py-6 border-b border-white/[0.06]">
            <h2 className="text-lg font-black text-white">Was ist in jedem Plan enthalten?</h2>
            <p className="mt-1 text-xs text-white/35">Ein vollständiger Überblick aller Features</p>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full min-w-[640px]">
              <thead>
                <tr className="border-b border-white/[0.06]">
                  <th className="py-4 px-8 text-left text-[10px] font-bold uppercase tracking-widest text-white/25 w-64">Feature</th>
                  {PLAN_ORDER.map((p) => {
                    const isCurrent = currentPlan === p;
                    return (
                      <th key={p} className="py-4 px-3 text-center">
                        <div className={cn('inline-flex flex-col items-center gap-1', isCurrent ? '' : 'opacity-60')}>
                          <PlanBadge plan={p} />
                          {isCurrent && (
                            <span className="text-[9px] font-bold text-violet-400">Dein Plan</span>
                          )}
                        </div>
                      </th>
                    );
                  })}
                </tr>
              </thead>
              <tbody>
                {categories.map((cat) => {
                  const rows = COMPARE_ROWS.filter(r => r.category === cat);
                  return (
                    <Fragment key={cat}>
                      {/* Category header row */}
                      <tr className="bg-white/[0.02] border-b border-white/[0.04]">
                        <td colSpan={6} className="px-8 py-2">
                          <span className="text-[10px] font-bold uppercase tracking-[0.18em] text-white/25">{cat}</span>
                        </td>
                      </tr>

                      {/* Feature rows */}
                      {rows.map((row) => {
                        const RowIcon = row.icon;
                        return (
                          <tr key={row.label} className="border-b border-white/[0.04] hover:bg-white/[0.02] transition-colors">
                            <td className="py-4 px-8">
                              <div className="flex items-start gap-3">
                                <RowIcon className="w-3.5 h-3.5 mt-0.5 text-white/25 flex-shrink-0" />
                                <div>
                                  <p className="text-sm font-medium text-white/75">{row.label}</p>
                                  {row.sub && <p className="text-[11px] text-white/30 mt-0.5">{row.sub}</p>}
                                </div>
                              </div>
                            </td>
                            {PLAN_ORDER.map((p) => {
                              const isCurrent = currentPlan === p;
                              return (
                                <td
                                  key={p}
                                  className={cn(
                                    'py-4 px-3 text-center',
                                    isCurrent ? 'bg-violet-500/[0.04]' : '',
                                  )}
                                >
                                  <CompareCell val={row.values[p]} isCurrent={isCurrent} />
                                </td>
                              );
                            })}
                          </tr>
                        );
                      })}
                    </Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Footer note */}
          <div className="px-8 py-5 border-t border-white/[0.05] flex items-center justify-between gap-4">
            <p className="text-xs text-white/30">
              Alle Preise exkl. MwSt. · Kündigung jederzeit möglich · Keine versteckten Kosten
            </p>
            <button
              onClick={() => void handleUpgrade('pro_plus')}
              className="shrink-0 flex items-center gap-2 rounded-xl border border-violet-500/[0.22] bg-violet-500/10 px-4 py-2 text-xs font-semibold text-violet-300 hover:bg-violet-500/20 transition-colors"
            >
              <Sparkles className="w-3.5 h-3.5" />
              Pro+ ausprobieren
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}
