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

type StripeInfo = {
  next_payment: number;
  amount_cents: number;
  currency: string;
  status: string;
};

type Licence = {
  id: string;
  email: string;
  plan: string;
  quota_month: number;
  usage_month: number;
  reset_at: string;
  active: boolean;
  flagged: boolean;
  created_at: string;
  stripe_customer_id: string | null;
  stripe_subscription_id: string | null;
  stripe_info: StripeInfo | null;
};

const PLAN_META: Record<string, { label: string; color: string; bg: string; defaultQuota: number }> = {
  trial:   { label: 'Trial',   color: '#d97706', bg: '#fffbeb', defaultQuota: 10 },
  gift:    { label: 'Gift',    color: '#2563eb', bg: '#eff6ff', defaultQuota: 20 },
  starter: { label: 'Starter', color: '#6b7280', bg: '#f9fafb', defaultQuota: 50 },
  pro:     { label: 'Pro',     color: '#7c3aed', bg: '#f5f3ff', defaultQuota: 500 },
  agency:  { label: 'Agency',  color: '#b45309', bg: '#fefce8', defaultQuota: 999999 },
};

function PlanBadge({ plan }: { plan: string }) {
  const m = PLAN_META[plan] ?? { label: plan, color: '#6b7280', bg: '#f9fafb', defaultQuota: 0 };
  return (
    <span style={{
      display: 'inline-block', padding: '2px 8px', borderRadius: 99,
      fontSize: 11, fontWeight: 700, letterSpacing: '0.04em',
      color: m.color, background: m.bg, border: `1px solid ${m.color}22`,
    }}>
      {m.label.toUpperCase()}
    </span>
  );
}

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: '2-digit' });
}

function formatUnix(ts: number) {
  return new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: '2-digit' });
}

function formatPrice(cents: number, currency: string) {
  return new Intl.NumberFormat('fr-FR', {
    style: 'currency', currency: currency.toUpperCase(), maximumFractionDigits: 0,
  }).format(cents / 100);
}

function StripeStatusBadge({ status }: { status: string }) {
  const map: Record<string, { label: string; color: string }> = {
    active:             { label: 'Actif',     color: '#059669' },
    past_due:           { label: 'En retard', color: '#dc2626' },
    canceled:           { label: 'Annulé',    color: '#9ca3af' },
    trialing:           { label: 'Trial',     color: '#d97706' },
    unpaid:             { label: 'Impayé',    color: '#dc2626' },
    incomplete:         { label: 'Incomplet', color: '#f59e0b' },
    incomplete_expired: { label: 'Expiré',    color: '#9ca3af' },
  };
  const s = map[status] ?? { label: status, color: '#6b7280' };
  return <span style={{ fontSize: 11, color: s.color, fontWeight: 600 }}>{s.label}</span>;
}

export default function AdminPage() {
  const [token,       setToken]       = useState('');
  const [inputToken,  setInputToken]  = useState('');
  const [licences,    setLicences]    = useState<Licence[]>([]);
  const [mrr,         setMrr]         = useState(0);
  const [loading,     setLoading]     = useState(false);
  const [authError,   setAuthError]   = useState('');
  const [showCreate,  setShowCreate]  = useState(false);
  const [newKey,      setNewKey]      = useState('');
  const [newKeyEmail, setNewKeyEmail] = useState('');
  const [copied,      setCopied]      = useState(false);

  const [cEmail, setCEmail] = useState('');
  const [cPlan,  setCPlan]  = useState('gift');
  const [cQuota, setCQuota] = useState(20);
  const [cBusy,  setCBusy]  = useState(false);
  const [cError, setCError] = useState('');

  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);

  useEffect(() => {
    const saved = sessionStorage.getItem('admin_token');
    if (saved) setToken(saved);
  }, []);

  const fetchLicences = useCallback(async (t: string) => {
    setLoading(true);
    try {
      const res = await fetch('/api/admin/licences', {
        headers: { Authorization: `Bearer ${t}` },
      });
      if (res.status === 401) { sessionStorage.removeItem('admin_token'); setToken(''); return; }
      const json = await res.json();
      setLicences(json.licences ?? []);
      setMrr(json.mrr ?? 0);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (token) fetchLicences(token);
  }, [token, fetchLicences]);

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setAuthError('');
    const res = await fetch('/api/admin/licences', {
      headers: { Authorization: `Bearer ${inputToken}` },
    });
    if (res.status === 401) { setAuthError('Mot de passe incorrect.'); return; }
    sessionStorage.setItem('admin_token', inputToken);
    setToken(inputToken);
  }

  async function toggleField(id: string, field: 'active' | 'flagged', value: boolean) {
    await fetch(`/api/admin/licences/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ [field]: value }),
    });
    setLicences(prev => prev.map(l => l.id === id ? { ...l, [field]: value } : l));
  }

  async function regenerateKey(id: string) {
    const res  = await fetch(`/api/admin/licences/${id}`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token}` },
    });
    const data = await res.json();
    if (data.key) {
      setNewKey(data.key);
      setNewKeyEmail(data.email);
      setShowCreate(false);
    }
  }

  async function deleteLicence(id: string) {
    await fetch(`/api/admin/licences/${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` },
    });
    setLicences(prev => prev.filter(l => l.id !== id));
    setConfirmDeleteId(null);
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    setCError('');
    setCBusy(true);
    try {
      const res  = await fetch('/api/admin/licences', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ email: cEmail, plan: cPlan, quota_month: cQuota }),
      });
      const data = await res.json();
      if (!data.key) { setCError(data.detail ?? data.error ?? 'Erreur'); return; }
      setNewKey(data.key);
      setNewKeyEmail(cEmail);
      setShowCreate(false);
      setCEmail('');
      await fetchLicences(token);
    } finally {
      setCBusy(false);
    }
  }

  function handleCopy() {
    navigator.clipboard.writeText(newKey);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  if (!token) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fafaf9' }}>
        <div style={{ background: '#fff', borderRadius: 16, padding: 32, boxShadow: '0 2px 24px rgba(0,0,0,.08)', width: 340 }}>
          <h1 style={{ fontSize: 18, fontWeight: 700, color: '#0f0f0f', margin: '0 0 4px' }}>Admin</h1>
          <p style={{ fontSize: 13, color: '#9ca3af', margin: '0 0 24px' }}>NoteToQuote</p>
          <form onSubmit={handleLogin}>
            <input
              type="password" required value={inputToken} onChange={e => setInputToken(e.target.value)}
              placeholder="Mot de passe admin"
              style={{ width: '100%', border: '1.5px solid #e9e7f0', borderRadius: 10, padding: '11px 14px', fontSize: 14, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box', marginBottom: 12 }}
            />
            {authError && <p style={{ fontSize: 12, color: '#dc2626', margin: '0 0 10px' }}>{authError}</p>}
            <button type="submit" style={{ width: '100%', padding: 11, borderRadius: 10, border: 'none', background: '#7c3aed', color: '#fff', fontWeight: 700, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit' }}>
              Connexion
            </button>
          </form>
        </div>
      </div>
    );
  }

  const stats = {
    total:   licences.length,
    actives: licences.filter(l => l.stripe_info?.status === 'active').length,
    trials:  licences.filter(l => l.plan === 'trial' || l.plan === 'gift').length,
    flagged: licences.filter(l => l.flagged).length,
  };

  const inputStyle: React.CSSProperties = {
    border: '1.5px solid #e9e7f0', borderRadius: 8, padding: '8px 12px',
    fontSize: 13, outline: 'none', fontFamily: 'inherit', background: '#fafaf9',
  };

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '32px 24px 80px' }}>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 22, fontWeight: 700, color: '#0f0f0f', margin: 0 }}>Admin</h1>
          <p style={{ fontSize: 13, color: '#9ca3af', margin: 0 }}>NoteToQuote · Gestion des licences</p>
        </div>
        <button
          onClick={() => { sessionStorage.removeItem('admin_token'); setToken(''); }}
          style={{ padding: '7px 14px', borderRadius: 8, border: '1px solid #e5e7eb', background: '#fff', color: '#6b7280', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}
        >
          Déconnexion
        </button>
      </div>

      <style>{`.stat-grid { display: grid; grid-template-columns: repeat(5,1fr); gap: 12; margin-bottom: 24px; } @media(max-width:640px){.stat-grid{grid-template-columns:repeat(2,1fr);}}`}</style>
      <div className="stat-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 24 }}>
        {[
          { label: 'Total licences', color: '#0f0f0f', fmt: String(stats.total) },
          { label: 'Payants actifs', color: '#059669', fmt: String(stats.actives) },
          { label: 'Trial / Gift',   color: '#d97706', fmt: String(stats.trials) },
          { label: 'Flaggées',       color: '#dc2626', fmt: String(stats.flagged) },
          { label: 'MRR',            color: '#7c3aed', fmt: `${mrr.toLocaleString('fr-FR')} €` },
        ].map(s => (
          <div key={s.label} style={{ background: '#fff', borderRadius: 12, padding: '16px 20px', boxShadow: '0 0 0 1px #f0eef8' }}>
            <div style={{ fontSize: 24, fontWeight: 800, color: s.color, lineHeight: 1 }}>{s.fmt}</div>
            <div style={{ fontSize: 12, color: '#9ca3af', marginTop: 4 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {newKey && (
        <div style={{ background: '#f0fdf4', border: '1.5px solid #86efac', borderRadius: 14, padding: 20, marginBottom: 20, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <p style={{ fontSize: 12, fontWeight: 600, color: '#166534', margin: '0 0 6px' }}>
              Clé créée pour <strong>{newKeyEmail}</strong> — notez-la maintenant, elle ne sera plus affichée
            </p>
            <code style={{ fontSize: 16, fontWeight: 800, color: '#14532d', letterSpacing: '0.06em', fontFamily: 'monospace' }}>
              {newKey}
            </code>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={handleCopy} style={{ padding: '7px 16px', borderRadius: 8, border: 'none', background: copied ? '#bbf7d0' : '#dcfce7', color: copied ? '#059669' : '#16a34a', fontWeight: 600, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
              {copied ? '✓ Copié' : 'Copier'}
            </button>
            <button onClick={() => setNewKey('')} style={{ padding: '7px 14px', borderRadius: 8, border: '1px solid #86efac', background: 'transparent', color: '#166534', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
              ✕
            </button>
          </div>
        </div>
      )}

      {showCreate ? (
        <div style={{ background: '#fff', borderRadius: 14, padding: 20, boxShadow: '0 0 0 1px #f0eef8', marginBottom: 20 }}>
          <p style={{ fontSize: 13, fontWeight: 600, color: '#0f0f0f', margin: '0 0 16px' }}>Nouvelle clé</p>
          <form onSubmit={handleCreate} style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Email</label>
              <input type="email" required value={cEmail} onChange={e => setCEmail(e.target.value)} placeholder="copain@email.com" style={{ ...inputStyle, width: 220 }} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Plan</label>
              <select value={cPlan} onChange={e => { const p = e.target.value; setCPlan(p); setCQuota(PLAN_META[p]?.defaultQuota ?? 20); }} style={{ ...inputStyle, cursor: 'pointer' }}>
                {Object.entries(PLAN_META).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
              </select>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <label style={{ fontSize: 11, fontWeight: 600, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Quota / mois</label>
              <input type="number" required min={1} max={999999} value={cQuota} onChange={e => setCQuota(Number(e.target.value))} style={{ ...inputStyle, width: 90 }} />
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button type="submit" disabled={cBusy} style={{ padding: '8px 18px', borderRadius: 8, border: 'none', background: '#7c3aed', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
                {cBusy ? '…' : 'Créer →'}
              </button>
              <button type="button" onClick={() => { setShowCreate(false); setCError(''); }} style={{ padding: '8px 14px', borderRadius: 8, border: '1px solid #e5e7eb', background: '#fff', color: '#6b7280', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
                Annuler
              </button>
            </div>
            {cError && <p style={{ fontSize: 12, color: '#dc2626', margin: 0, alignSelf: 'center' }}>{cError}</p>}
          </form>
        </div>
      ) : (
        <div style={{ marginBottom: 16 }}>
          <button onClick={() => { setShowCreate(true); setNewKey(''); }} style={{ padding: '9px 18px', borderRadius: 10, border: 'none', background: '#7c3aed', color: '#fff', fontWeight: 700, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
            + Créer une clé
          </button>
          <button onClick={() => fetchLicences(token)} style={{ marginLeft: 10, padding: '9px 14px', borderRadius: 10, border: '1px solid #e5e7eb', background: '#fff', color: '#6b7280', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>
            ↻ Rafraîchir
          </button>
        </div>
      )}

      <div style={{ background: '#fff', borderRadius: 14, boxShadow: '0 0 0 1px #f0eef8', overflow: 'hidden' }}>
        <style>{`
          @media (max-width: 768px) {
            .col-price, .col-stripe, .col-next, .col-date, .col-flag { display: none; }
          }
        `}</style>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#9ca3af', fontSize: 13 }}>Chargement…</div>
        ) : licences.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#9ca3af', fontSize: 13 }}>Aucune licence</div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 400 }}>
            <thead>
              <tr style={{ background: '#fafaf9', borderBottom: '1px solid #f0eef8' }}>
                {[
                  { h: 'Email',             cls: '' },
                  { h: 'Plan',              cls: '' },
                  { h: 'Usage',             cls: '' },
                  { h: 'Prix / mois',       cls: 'col-price' },
                  { h: 'Statut Stripe',     cls: 'col-stripe' },
                  { h: 'Prochain paiement', cls: 'col-next' },
                  { h: 'Actif',             cls: '' },
                  { h: 'Flaggé',            cls: 'col-flag' },
                  { h: 'Créé le',           cls: 'col-date' },
                  { h: '',                  cls: '' },
                  { h: '',                  cls: '' },
                ].map(({ h, cls }) => (
                  <th key={h + cls} className={cls} style={{ padding: '10px 14px', textAlign: 'left', fontWeight: 600, color: '#9ca3af', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', whiteSpace: 'nowrap' }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {licences.map((l, i) => (
                <tr key={l.id} style={{ borderBottom: i < licences.length - 1 ? '1px solid #f9f8ff' : 'none', background: l.flagged ? '#fff5f5' : 'transparent' }}>
                  <td style={{ padding: '11px 14px', color: '#0f0f0f', maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {l.email}
                  </td>
                  <td style={{ padding: '11px 14px' }}>
                    <PlanBadge plan={l.plan} />
                  </td>
                  <td style={{ padding: '11px 14px', color: l.usage_month >= l.quota_month ? '#dc2626' : '#374151', fontWeight: l.usage_month >= l.quota_month ? 700 : 400, fontVariantNumeric: 'tabular-nums' }}>
                    {l.quota_month >= 999999 ? `${l.usage_month} / ∞` : `${l.usage_month} / ${l.quota_month}`}
                  </td>
                  <td className="col-price" style={{ padding: '11px 14px', fontWeight: 600, color: l.stripe_info ? '#0f0f0f' : '#d1d5db' }}>
                    {l.stripe_info ? formatPrice(l.stripe_info.amount_cents, l.stripe_info.currency) : '—'}
                  </td>
                  <td className="col-stripe" style={{ padding: '11px 14px' }}>
                    {l.stripe_info
                      ? <StripeStatusBadge status={l.stripe_info.status} />
                      : <span style={{ color: '#d1d5db', fontSize: 12 }}>—</span>}
                  </td>
                  <td className="col-next" style={{ padding: '11px 14px', color: '#374151', whiteSpace: 'nowrap' }}>
                    {l.stripe_info && l.stripe_info.status !== 'canceled'
                      ? formatUnix(l.stripe_info.next_payment)
                      : <span style={{ color: '#d1d5db' }}>—</span>}
                  </td>
                  <td style={{ padding: '11px 14px' }}>
                    <button
                      onClick={() => toggleField(l.id, 'active', !l.active)}
                      title={l.active ? 'Désactiver' : 'Activer'}
                      style={{ width: 28, height: 16, borderRadius: 99, border: 'none', cursor: 'pointer', background: l.active ? '#10b981' : '#e5e7eb', padding: 0, position: 'relative', display: 'inline-block' }}
                    >
                      <span style={{ position: 'absolute', top: 2, left: l.active ? 14 : 2, width: 12, height: 12, borderRadius: '50%', background: '#fff', transition: 'left .15s' }} />
                    </button>
                  </td>
                  <td className="col-flag" style={{ padding: '11px 14px' }}>
                    <button
                      onClick={() => toggleField(l.id, 'flagged', !l.flagged)}
                      title={l.flagged ? 'Retirer le flag' : 'Flagguer'}
                      style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 16, opacity: l.flagged ? 1 : 0.25, padding: 0 }}
                    >
                      🚩
                    </button>
                  </td>
                  <td className="col-date" style={{ padding: '11px 14px', color: '#9ca3af', whiteSpace: 'nowrap' }}>
                    {formatDate(l.created_at)}
                  </td>
                  <td style={{ padding: '11px 14px' }}>
                    <button
                      onClick={() => regenerateKey(l.id)}
                      title="Régénérer la clé"
                      style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 15, padding: 0, color: '#d1d5db' }}
                      onMouseEnter={e => (e.currentTarget.style.color = '#7c3aed')}
                      onMouseLeave={e => (e.currentTarget.style.color = '#d1d5db')}
                    >
                      🔑
                    </button>
                  </td>
                  <td style={{ padding: '11px 14px' }}>
                    {confirmDeleteId === l.id ? (
                      <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        <button
                          onClick={() => deleteLicence(l.id)}
                          style={{ padding: '3px 8px', borderRadius: 6, border: 'none', background: '#dc2626', color: '#fff', fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}
                        >
                          Confirmer
                        </button>
                        <button
                          onClick={() => setConfirmDeleteId(null)}
                          style={{ padding: '3px 8px', borderRadius: 6, border: '1px solid #e5e7eb', background: '#fff', color: '#6b7280', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit' }}
                        >
                          ✕
                        </button>
                      </span>
                    ) : (
                      <button
                        onClick={() => setConfirmDeleteId(l.id)}
                        title="Supprimer cette licence"
                        style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: '#d1d5db', fontSize: 15, padding: 0, lineHeight: 1 }}
                        onMouseEnter={e => (e.currentTarget.style.color = '#dc2626')}
                        onMouseLeave={e => (e.currentTarget.style.color = '#d1d5db')}
                      >
                        🗑
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        )}
      </div>
    </div>
  );
}
