'use client';
import { useState, useEffect } from 'react';

type LicenceData = {
  plan:        string;
  quota_month: number;
  usage_month: number;
  reset_at:    string;
  active:      boolean;
  flagged:     boolean;
  created_at:  string;
};

const PLAN_META: Record<string, { label: string; color: string; bg: string }> = {
  starter:   { label: 'Solo',      color: '#374151', bg: '#f3f4f6' },
  essentiel: { label: 'Essentiel', color: '#0369a1', bg: '#e0f2fe' },
  pro:       { label: 'Pro',       color: '#6d28d9', bg: '#f5f3ff' },
  agency:    { label: 'Agence',    color: '#92400e', bg: '#fef3c7' },
  trial:     { label: 'Essai',     color: '#1e40af', bg: '#dbeafe' },
};

export default function DashboardPage() {
  const [key,           setKey]           = useState('');
  const [licence,       setLicence]       = useState<LicenceData | null>(null);
  const [error,         setError]         = useState('');
  const [loading,       setLoading]       = useState(false);
  const [dlLoading,     setDlLoading]     = useState(false);
  const [copied,        setCopied]        = useState(false);
  const [portalLoading, setPortalLoading] = useState(false);
  const [initializing,  setInitializing]  = useState(true);

  useEffect(() => {
    const saved = localStorage.getItem('ntq_key');
    if (saved && /^LAU-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(saved)) {
      setKey(saved);
      fetch(`/api/licence?key=${encodeURIComponent(saved)}`)
        .then(r => r.json().then((data: LicenceData) => ({ ok: r.ok, data })))
        .then(({ ok, data }) => {
          if (ok) setLicence(data);
          else localStorage.removeItem('ntq_key');
        })
        .catch(() => {})
        .finally(() => setInitializing(false));
    } else {
      setInitializing(false);
    }
  }, []);

  async function handleLookup(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setLicence(null);
    setLoading(true);
    try {
      const res  = await fetch(`/api/licence?key=${encodeURIComponent(key.trim().toUpperCase())}`);
      const data = await res.json();
      if (!res.ok) {
        setError(data.error === 'not_found' ? 'Clé introuvable.' : 'Format de clé invalide.');
        return;
      }
      setLicence(data);
      localStorage.setItem('ntq_key', key.trim().toUpperCase());
    } catch {
      setError('Erreur réseau — réessayez.');
    } finally {
      setLoading(false);
    }
  }

  async function handleDownload() {
    setDlLoading(true);
    setError('');
    try {
      const res = await fetch(`/api/download?key=${encodeURIComponent(key.trim().toUpperCase())}`);
      if (!res.ok) {
        const d = await res.json();
        setError(d.error === 'licence_invalid' ? 'Licence inactive.' : 'Module introuvable sur le serveur.');
        return;
      }
      const blob = await res.blob();
      const url  = URL.createObjectURL(blob);
      const a    = document.createElement('a');
      a.href     = url;
      a.download = 'module_notetoquote-1.0.0.zip';
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      setError('Erreur lors du téléchargement.');
    } finally {
      setDlLoading(false);
    }
  }

  async function handleCopy() {
    await navigator.clipboard.writeText(key.trim().toUpperCase());
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  async function handlePortal() {
    setPortalLoading(true);
    setError('');
    try {
      const res  = await fetch(`/api/portal?key=${encodeURIComponent(key.trim().toUpperCase())}`);
      const data = await res.json();
      if (data.url) { window.location.href = data.url; return; }
      setError('Impossible d\'accéder au portail de facturation.');
    } catch {
      setError('Erreur réseau — réessayez.');
    } finally {
      setPortalLoading(false);
    }
  }

  const usagePct  = licence ? Math.min(100, Math.round((licence.usage_month / licence.quota_month) * 100)) : 0;
  const resetDate = licence
    ? new Date(licence.reset_at).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long' })
    : '';
  const planMeta = licence ? (PLAN_META[licence.plan] ?? PLAN_META.trial) : null;

  /* ── Initializing ────────────────────────────────────────────────────── */
  if (initializing) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 320 }}>
        <svg style={{ animation: 'spin 1s linear infinite' }} width={28} height={28} fill="none" viewBox="0 0 24 24">
          <circle cx={12} cy={12} r={10} stroke="#ddd6fe" strokeWidth={4} />
          <path fill="#7c3aed" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  /* ── Login screen ─────────────────────────────────────────────────────── */
  if (!licence) {
    return (
      <div style={{ padding: '64px 24px 64px', display: 'flex', justifyContent: 'center' }}>
        <div style={{ maxWidth: 380, width: '100%' }}>

          <div style={{ textAlign: 'center', marginBottom: 28 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16,
              background: 'linear-gradient(135deg, #6d28d9, #8b5cf6)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 16px',
              boxShadow: '0 6px 20px rgba(109,40,217,.30)',
            }}>
              <svg width={24} height={24} fill="none" viewBox="0 0 24 24" stroke="#fff" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
              </svg>
            </div>
            <h1 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.03em', color: '#0f0f0f', margin: '0 0 6px' }}>
              Mon espace client
            </h1>
            <p style={{ fontSize: 13, color: '#9ca3af', margin: 0 }}>
              Entrez votre clé de licence pour accéder à votre espace.
            </p>
          </div>

          <form onSubmit={handleLookup} style={{ background: '#fff', borderRadius: 20, padding: 28, boxShadow: '0 0 0 1px #f0eef8, 0 4px 24px rgba(109,40,217,.08)' }}>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
              Clé de licence
            </label>
            <input
              type="text"
              value={key}
              onChange={e => setKey(e.target.value)}
              placeholder="LAU-XXXX-XXXX-XXXX"
              pattern="[A-Za-z0-9]{3}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}"
              required
              style={{
                width: '100%', border: '1.5px solid #e9e7f0', borderRadius: 12,
                padding: '12px 16px', fontSize: 14, fontFamily: 'monospace',
                color: '#0f0f0f', background: '#fafaf9', outline: 'none',
                marginBottom: 16, letterSpacing: '0.1em', textTransform: 'uppercase',
                transition: 'all .15s', boxSizing: 'border-box',
              }}
              onFocus={e => { e.currentTarget.style.borderColor = '#7c3aed'; e.currentTarget.style.boxShadow = '0 0 0 3px rgba(124,58,237,.12)'; e.currentTarget.style.background = '#fff'; }}
              onBlur={e => { e.currentTarget.style.borderColor = '#e9e7f0'; e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.background = '#fafaf9'; }}
            />

            {error && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: '#dc2626', background: '#fff5f5', border: '1px solid #fecaca', borderRadius: 10, padding: '10px 14px', marginBottom: 14 }}>
                <svg width={15} height={15} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              style={{
                width: '100%', padding: 13, borderRadius: 12, border: 'none',
                background: loading ? '#a78bfa' : 'linear-gradient(135deg, #6d28d9, #7c3aed, #a855f7)',
                color: '#fff', fontWeight: 700, fontSize: 14, cursor: loading ? 'default' : 'pointer',
                boxShadow: loading ? 'none' : '0 4px 14px rgba(109,40,217,.40)',
                letterSpacing: '-0.01em', fontFamily: 'inherit',
              }}
            >
              {loading ? (
                <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                  <svg style={{ animation: 'spin 1s linear infinite' }} width={16} height={16} fill="none" viewBox="0 0 24 24">
                    <circle cx={12} cy={12} r={10} stroke="currentColor" strokeWidth={4} strokeOpacity={.25} />
                    <path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                  </svg>
                  Vérification…
                </span>
              ) : 'Accéder à mon espace →'}
            </button>

            <p style={{ textAlign: 'center', fontSize: 12, color: '#c4b5fd', marginTop: 14 }}>
              Clé reçue par email après paiement.
            </p>
          </form>
        </div>
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  /* ── Dashboard ────────────────────────────────────────────────────────── */
  const card: React.CSSProperties = {
    background: '#fff', borderRadius: 16, padding: 24, marginBottom: 12,
    boxShadow: '0 0 0 1px #f0eef8, 0 4px 16px rgba(0,0,0,.04)',
  };

  return (
    <div style={{ maxWidth: 480, margin: '0 auto', padding: '48px 24px 64px' }}>

      {/* Account header */}
      <div style={{ ...card, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: 40, height: 40, borderRadius: '50%',
            background: 'linear-gradient(135deg, #6d28d9, #a855f7)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontWeight: 800, fontSize: 15, flexShrink: 0,
          }}>
            #
          </div>
          <div style={{ minWidth: 0 }}>
            <p style={{ margin: 0, fontWeight: 700, fontSize: 13, color: '#0f0f0f', fontFamily: 'monospace', letterSpacing: '0.05em' }}>
              {key.trim().toUpperCase()}
            </p>
            <p style={{ margin: 0, fontSize: 11, color: '#9ca3af' }}>
              Activé le {new Date(licence.created_at).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', year: 'numeric' })}
            </p>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0, marginLeft: 12 }}>
          <span style={{
            fontSize: 11, fontWeight: 700, padding: '4px 10px', borderRadius: 99,
            color: planMeta!.color, background: planMeta!.bg,
          }}>
            {planMeta!.label}
          </span>
          <span style={{
            fontSize: 11, fontWeight: 700, padding: '4px 10px', borderRadius: 99,
            color: licence.active && !licence.flagged ? '#059669' : '#dc2626',
            background: licence.active && !licence.flagged ? '#ecfdf5' : '#fff5f5',
          }}>
            {licence.flagged ? '● Suspendu' : licence.active ? '● Actif' : '● Inactif'}
          </span>
        </div>
      </div>

      {/* Quota */}
      <div style={card}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16 }}>
          <div>
            <p style={{ margin: '0 0 4px', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              {licence.plan === 'trial' ? 'Devis restants' : 'Devis ce mois'}
            </p>
            <p style={{ margin: 0, fontSize: 28, fontWeight: 900, letterSpacing: '-0.04em', color: '#0f0f0f', lineHeight: 1 }}>
              {licence.usage_month}
              <span style={{ fontSize: 15, fontWeight: 400, color: '#9ca3af' }}>
                {' '}/ {licence.quota_month >= 99999 ? '∞' : licence.quota_month}
              </span>
            </p>
          </div>
          {licence.plan !== 'trial' && (
            <div style={{ textAlign: 'right' }}>
              <p style={{ margin: 0, fontSize: 11, color: '#9ca3af' }}>Remise à zéro le</p>
              <p style={{ margin: 0, fontSize: 13, fontWeight: 700, color: '#374151' }}>{resetDate}</p>
            </div>
          )}
        </div>

        {licence.quota_month < 99999 ? (
          <>
            <div style={{ width: '100%', background: '#f3f4f6', borderRadius: 99, height: 6, overflow: 'hidden' }}>
              <div style={{
                height: '100%', borderRadius: 99,
                width: `${usagePct}%`,
                background: usagePct >= 90
                  ? 'linear-gradient(90deg, #ef4444, #dc2626)'
                  : usagePct >= 70
                    ? 'linear-gradient(90deg, #f59e0b, #d97706)'
                    : 'linear-gradient(90deg, #6d28d9, #a855f7)',
                transition: 'width .5s ease',
              }} />
            </div>
            <p style={{ margin: '6px 0 0', fontSize: 11, color: '#9ca3af' }}>{usagePct}% utilisé</p>
          </>
        ) : (
          <p style={{ margin: 0, fontSize: 13, color: '#7c3aed', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
            <svg width={14} height={14} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            Devis illimités
          </p>
        )}
      </div>

      {/* Download */}
      <div style={card}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
          <div style={{ minWidth: 0 }}>
            <p style={{ margin: '0 0 3px', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              Module Dolibarr
            </p>
            <p style={{ margin: '0 0 4px', fontWeight: 700, fontSize: 13, color: '#0f0f0f' }}>module_notetoquote-1.0.0.zip</p>
            <p style={{ margin: 0, fontSize: 11, color: '#9ca3af' }}>
              Dolibarr → Configuration → Modules → Déployer
            </p>
          </div>
          <button
            onClick={handleDownload}
            disabled={!licence.active || dlLoading}
            style={{
              flexShrink: 0, display: 'flex', alignItems: 'center', gap: 8,
              fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 12, border: 'none',
              cursor: licence.active && !dlLoading ? 'pointer' : 'default',
              background: licence.active ? 'linear-gradient(135deg, #6d28d9, #a855f7)' : '#f3f4f6',
              color: licence.active ? '#fff' : '#9ca3af',
              boxShadow: licence.active ? '0 3px 10px rgba(109,40,217,.30)' : 'none',
              opacity: dlLoading ? 0.7 : 1,
              fontFamily: 'inherit',
            }}
          >
            {dlLoading ? (
              <svg style={{ animation: 'spin 1s linear infinite' }} width={16} height={16} fill="none" viewBox="0 0 24 24">
                <circle cx={12} cy={12} r={10} stroke="currentColor" strokeWidth={4} strokeOpacity={.25} />
                <path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
            ) : (
              <svg width={16} height={16} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
            )}
            {dlLoading ? 'En cours…' : 'Télécharger'}
          </button>
        </div>
        {error && (
          <p style={{ margin: '12px 0 0', fontSize: 12, color: '#dc2626', display: 'flex', alignItems: 'center', gap: 6 }}>
            <svg width={13} height={13} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            {error}
          </p>
        )}
      </div>

      {/* Licence key */}
      <div style={{ ...card, marginBottom: 28 }}>
        <p style={{ margin: '0 0 12px', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
          Clé de licence
        </p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <code style={{
            flex: 1, minWidth: 0,
            background: '#fafaf9', border: '1.5px solid #f0eef8', borderRadius: 12,
            padding: '11px 14px', fontSize: 13, fontFamily: 'monospace',
            letterSpacing: '0.08em', color: '#374151',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {key.trim().toUpperCase()}
          </code>
          <button
            onClick={handleCopy}
            style={{
              flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6,
              fontSize: 12, fontWeight: 700, padding: '11px 14px', borderRadius: 12,
              border: `1.5px solid ${copied ? '#a7f3d0' : '#e9e7f0'}`,
              background: copied ? '#ecfdf5' : '#fff',
              color: copied ? '#059669' : '#6b7280',
              cursor: 'pointer', fontFamily: 'inherit', transition: 'all .2s',
            }}
          >
            {copied ? (
              <svg width={15} height={15} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
              </svg>
            ) : (
              <svg width={15} height={15} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            )}
            {copied ? 'Copié !' : 'Copier'}
          </button>
        </div>
        <p style={{ margin: '8px 0 0', fontSize: 11, color: '#c4b5fd' }}>
          Dolibarr → NoteToQuote → Configuration → Clé de licence
        </p>
      </div>

      {licence.plan === 'trial' && (
        <div style={{ ...card, marginBottom: 28, background: 'linear-gradient(135deg, #f5f3ff, #fdf4ff)', border: '1px solid #ddd6fe' }}>
          <p style={{ margin: '0 0 4px', fontSize: 11, fontWeight: 700, color: '#7c3aed', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            Passer à un forfait
          </p>
          <p style={{ margin: '0 0 16px', fontSize: 13, color: '#374151', lineHeight: 1.55 }}>
            L&apos;essai vous convient ? Choisissez un forfait pour continuer sans limite mensuelle.
          </p>
          <a
            href="/#plans"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              fontSize: 13, fontWeight: 700, padding: '10px 18px', borderRadius: 12,
              background: 'linear-gradient(135deg, #6d28d9, #7c3aed)',
              color: '#fff', textDecoration: 'none',
              boxShadow: '0 3px 10px rgba(109,40,217,.30)',
              fontFamily: 'inherit',
            }}
          >
            Voir les forfaits →
          </a>
        </div>
      )}

      {['starter', 'essentiel', 'pro', 'agency'].includes(licence.plan) && (
        <div style={{ ...card, marginBottom: 28 }}>
          <p style={{ margin: '0 0 4px', fontSize: 11, fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            Abonnement
          </p>
          <p style={{ margin: '0 0 14px', fontSize: 13, color: '#374151' }}>
            Consultez vos factures ou résiliez votre abonnement en quelques clics.
          </p>
          <button
            onClick={handlePortal}
            disabled={portalLoading}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              fontSize: 13, fontWeight: 600, padding: '10px 18px', borderRadius: 12,
              border: '1.5px solid #e9e7f0', background: '#fff',
              color: portalLoading ? '#9ca3af' : '#374151',
              cursor: portalLoading ? 'default' : 'pointer', fontFamily: 'inherit',
            }}
          >
            {portalLoading ? (
              <svg style={{ animation: 'spin 1s linear infinite' }} width={15} height={15} fill="none" viewBox="0 0 24 24">
                <circle cx={12} cy={12} r={10} stroke="currentColor" strokeWidth={4} strokeOpacity={.25} />
                <path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
            ) : (
              <svg width={15} height={15} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
            )}
            {portalLoading ? 'Redirection…' : 'Gérer mon abonnement →'}
          </button>
        </div>
      )}

      <div style={{ textAlign: 'center' }}>
        <button
          onClick={() => { setLicence(null); setKey(''); setError(''); localStorage.removeItem('ntq_key'); }}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            fontSize: 13, color: '#9ca3af', background: 'none', border: 'none',
            cursor: 'pointer', fontFamily: 'inherit',
          }}
        >
          <svg width={14} height={14} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
          </svg>
          Utiliser une autre clé
        </button>
      </div>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}
