import { stripe, PLANS } from '@/lib/stripe';
import Link from 'next/link';

export default async function SuccessPage({
  searchParams,
}: {
  searchParams: Promise<{ session_id?: string }>;
}) {
  const { session_id } = await searchParams;

  if (!session_id) {
    return <Fallback message="Paramètre session manquant." />;
  }

  let email    = '';
  let planName = '';
  let trialEnd = '';
  let ok       = false;

  try {
    const session = await stripe.checkout.sessions.retrieve(session_id, {
      expand: ['subscription'],
    });
    email    = session.customer_email ?? (session.customer_details?.email ?? '');
    const pk = (session.metadata?.plan ?? 'pro') as keyof typeof PLANS;
    planName = PLANS[pk]?.name ?? pk;
    const sub = session.subscription as { trial_end?: number | null } | null;
    if (sub?.trial_end) {
      trialEnd = new Date(sub.trial_end * 1000).toLocaleDateString('fr-FR', {
        day: '2-digit', month: 'long', year: 'numeric',
      });
    }
    ok = !!(email && planName);
  } catch {
    // Session expirée ou invalide
  }

  if (!ok) {
    return <Fallback message="Session expirée ou invalide. Vérifiez votre email pour retrouver votre clé de licence." />;
  }

  const steps = [
    'Vérifiez votre boîte email (et les spams)',
    'Copiez votre clé de licence (format LAU-XXXX-XXXX-XXXX)',
    'Connectez-vous à votre espace client et téléchargez le module',
    'Dans Dolibarr → NoteToQuote → Configurer → Collez la clé et enregistrez',
  ];

  return (
    <div style={{ minHeight: 'calc(100vh - 140px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px 24px' }}>
      <div style={{ maxWidth: 440, width: '100%', textAlign: 'center' }}>

        <div style={{ position: 'relative', display: 'inline-flex', marginBottom: 28 }}>
          <div style={{
            width: 72, height: 72, borderRadius: '50%',
            background: 'linear-gradient(135deg, #059669, #10b981)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 8px 30px rgba(16,185,129,.28)',
          }}>
            <svg width={36} height={36} fill="none" viewBox="0 0 24 24" stroke="#fff" strokeWidth={2.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
            </svg>
          </div>
        </div>

        <h1 style={{ fontSize: 30, fontWeight: 800, letterSpacing: '-0.03em', color: '#0f0f0f', margin: '0 0 8px' }}>
          Bienvenue !
        </h1>
        {trialEnd && (
          <p style={{ fontSize: 14, color: '#6b7280', margin: '0 0 4px' }}>
            Essai gratuit jusqu&apos;au <strong style={{ color: '#374151' }}>{trialEnd}</strong>
          </p>
        )}
        <p style={{ fontSize: 14, color: '#9ca3af', margin: '0 0 16px' }}>
          Votre clé de licence a été envoyée à <strong style={{ color: '#6b7280' }}>{email}</strong>
        </p>
        <span style={{
          display: 'inline-block', fontSize: 11, fontWeight: 700,
          color: '#6d28d9', background: '#f5f3ff', border: '1px solid #ddd6fe',
          padding: '4px 12px', borderRadius: 99, marginBottom: 28,
        }}>
          Plan {planName} activé
        </span>

        <div style={{ background: '#fff', borderRadius: 16, padding: 24, textAlign: 'left', marginBottom: 24, boxShadow: '0 0 0 1px #f0eef8, 0 4px 20px rgba(0,0,0,.05)' }}>
          <p style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em', margin: '0 0 16px' }}>
            Prochaines étapes
          </p>
          <ol style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {steps.map((s, i) => (
              <li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                <span style={{
                  flexShrink: 0, width: 22, height: 22, borderRadius: '50%',
                  background: 'linear-gradient(135deg, #7c3aed, #a855f7)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontSize: 11, fontWeight: 700, marginTop: 1,
                }}>{i + 1}</span>
                <span style={{ fontSize: 13, color: '#4b5563', lineHeight: 1.5 }}>{s}</span>
              </li>
            ))}
          </ol>
        </div>

        <Link
          href="/dashboard"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            color: '#fff', fontWeight: 700, fontSize: 14,
            padding: '13px 28px', borderRadius: 12, textDecoration: 'none',
            background: 'linear-gradient(135deg, #6d28d9, #7c3aed, #a855f7)',
            boxShadow: '0 4px 14px rgba(109,40,217,.40)',
          }}
        >
          Accéder à mon espace →
        </Link>
      </div>
    </div>
  );
}

function Fallback({ message }: { message: string }) {
  return (
    <div style={{ minHeight: 'calc(100vh - 140px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ textAlign: 'center', maxWidth: 380 }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#fef3c7', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 20px' }}>
          <svg width={24} height={24} fill="none" viewBox="0 0 24 24" stroke="#d97706" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
        </div>
        <p style={{ fontSize: 14, color: '#6b7280', marginBottom: 20, lineHeight: 1.6 }}>{message}</p>
        <Link href="/dashboard" style={{ color: '#7c3aed', fontWeight: 600, textDecoration: 'none', fontSize: 14 }}>
          Accéder à mon espace →
        </Link>
      </div>
    </div>
  );
}
