import { useState, useEffect, useCallback } from 'react';
import {
  Users, DollarSign, AlertTriangle, XCircle,
  CheckCircle, PauseCircle, Plus, Trash2, Edit2, X, ChevronDown,
  Tag, FileText, HelpCircle, GripVertical, ToggleLeft, ToggleRight,
} from 'lucide-react';
import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts';
import { ClubService } from '../services/api';

// ── Types ─────────────────────────────────────────────────────────────────────

interface ClubMember {
  id: number;
  user_cpf: string;
  user_nome: string;
  user_telefone: string | null;
  user_email: string | null;
  status: 'active' | 'suspended' | 'canceled' | 'pending_payment';
  plan_name: string;
  price_monthly: number;
  next_billing_at: string | null;
  started_at: string;
}

interface ClubPartner {
  id: number;
  name: string;
  specialty: string | null;
  phone: string | null;
  address: string | null;
  discount_percent: number;
  notes: string | null;
  active: boolean;
}

interface ClubPlan {
  id: number;
  club_id: number;
  name: string;
  description: string | null;
  price_monthly: number;
  max_dependents: number;
  features: string[];
  active: boolean;
}

interface ClubFaq {
  id: number;
  club_id: number;
  question: string;
  answer: string;
  sort_order: number;
  active: boolean;
}

interface Props {
  clubId: number;
  clubName: string;
  clubSlug: string;
  accentColor: string;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

const STATUS_LABEL: Record<string, string> = {
  active: 'Ativo',
  suspended: 'Suspenso',
  canceled: 'Cancelado',
  pending_payment: 'Aguard. Pgto',
};

const STATUS_STYLE: Record<string, string> = {
  active: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
  suspended: 'bg-amber-500/10 text-amber-400 border-amber-500/20',
  canceled: 'bg-rose-500/10 text-rose-400 border-rose-500/20',
  pending_payment: 'bg-slate-500/10 text-slate-400 border-slate-500/20',
};

function StatusBadge({ status }: { status: string }) {
  return (
    <span className={`text-[10px] font-bold px-2 py-0.5 rounded border ${STATUS_STYLE[status] || 'bg-slate-700 text-slate-400'}`}>
      {STATUS_LABEL[status] || status}
    </span>
  );
}

function fmtCurrency(v: number) {
  return `R$ ${Number(v).toFixed(2).replace('.', ',')}`;
}

function fmtDate(s: string | null) {
  if (!s) return '—';
  return new Date(s).toLocaleDateString('pt-BR');
}

function fmtCpf(cpf: string) {
  return cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
}

// ── Partner Modal ─────────────────────────────────────────────────────────────

function PartnerModal({
  clubId, partner, onClose, onSaved,
}: {
  clubId: number;
  partner: ClubPartner | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [form, setForm] = useState({
    name: partner?.name || '',
    specialty: partner?.specialty || '',
    phone: partner?.phone || '',
    address: partner?.address || '',
    discount_percent: partner?.discount_percent ?? 0,
    notes: partner?.notes || '',
    active: partner?.active ?? true,
  });
  const [saving, setSaving] = useState(false);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      if (partner) {
        await ClubService.updatePartner(partner.id, form);
      } else {
        await ClubService.createPartner({ ...form, club_id: clubId });
      }
      onSaved();
      onClose();
    } catch {
      alert('Erro ao salvar parceiro');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-md">
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <h3 className="text-lg font-black text-white">{partner ? 'Editar Parceiro' : 'Novo Parceiro'}</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors"><X size={20} /></button>
        </div>
        <form onSubmit={submit} className="p-6 space-y-4">
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Nome *</label>
            <input
              required value={form.name}
              onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Especialidade</label>
              <input
                value={form.specialty}
                onChange={e => setForm(f => ({ ...f, specialty: e.target.value }))}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
              />
            </div>
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Desconto %</label>
              <input
                type="number" min={0} max={100} value={form.discount_percent}
                onChange={e => setForm(f => ({ ...f, discount_percent: Number(e.target.value) }))}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
              />
            </div>
          </div>
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Telefone</label>
            <input
              value={form.phone}
              onChange={e => setForm(f => ({ ...f, phone: e.target.value }))}
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
            />
          </div>
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Endereço</label>
            <input
              value={form.address}
              onChange={e => setForm(f => ({ ...f, address: e.target.value }))}
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
            />
          </div>
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Observações</label>
            <textarea
              value={form.notes} rows={2}
              onChange={e => setForm(f => ({ ...f, notes: e.target.value }))}
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 resize-none"
            />
          </div>
          {partner && (
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox" checked={form.active}
                onChange={e => setForm(f => ({ ...f, active: e.target.checked }))}
                className="accent-cyan-500"
              />
              <span className="text-sm text-slate-300">Parceiro ativo</span>
            </label>
          )}
          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="flex-1 py-2.5 rounded-xl border border-slate-700 text-slate-400 hover:text-white text-sm font-bold transition-colors">
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              className="flex-1 py-2.5 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-black text-sm font-black transition-colors disabled:opacity-50">
              {saving ? 'Salvando…' : 'Salvar'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Plan Modal ────────────────────────────────────────────────────────────────

function PlanModal({
  clubId, plan, onClose, onSaved,
}: {
  clubId: number;
  plan: ClubPlan | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [form, setForm] = useState({
    name: plan?.name || '',
    description: plan?.description || '',
    price_monthly: plan?.price_monthly ?? 0,
    max_dependents: plan?.max_dependents ?? 0,
    features: plan?.features ? [...plan.features] : [''],
    active: plan?.active ?? true,
  });
  const [saving, setSaving] = useState(false);

  function addFeature() {
    setForm(f => ({ ...f, features: [...f.features, ''] }));
  }

  function removeFeature(i: number) {
    setForm(f => ({ ...f, features: f.features.filter((_, idx) => idx !== i) }));
  }

  function setFeature(i: number, val: string) {
    setForm(f => {
      const features = [...f.features];
      features[i] = val;
      return { ...f, features };
    });
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const payload = {
        ...form,
        club_id: clubId,
        features: form.features.filter(f => f.trim()),
      };
      if (plan) {
        await ClubService.updatePlan(plan.id, payload);
      } else {
        await ClubService.createPlan(payload);
      }
      onSaved();
      onClose();
    } catch {
      alert('Erro ao salvar plano');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-6 border-b border-slate-800 sticky top-0 bg-slate-900 z-10">
          <h3 className="text-lg font-black text-white">{plan ? 'Editar Plano' : 'Novo Plano'}</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors"><X size={20} /></button>
        </div>
        <form onSubmit={submit} className="p-6 space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Nome do Plano *</label>
              <input
                required value={form.name}
                onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                placeholder="Ex: Pessoal, Família..."
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
              />
            </div>
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Preço Mensal (R$) *</label>
              <input
                required type="number" min={0} step="0.01" value={form.price_monthly}
                onChange={e => setForm(f => ({ ...f, price_monthly: Number(e.target.value) }))}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
              />
            </div>
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Máx. Dependentes</label>
              <input
                type="number" min={0} value={form.max_dependents}
                onChange={e => setForm(f => ({ ...f, max_dependents: Number(e.target.value) }))}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
              />
            </div>
          </div>
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Descrição</label>
            <input
              value={form.description}
              onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
              placeholder="Breve descrição do plano..."
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
            />
          </div>

          {/* Features */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Benefícios incluídos</label>
              <button type="button" onClick={addFeature}
                className="text-xs font-black text-cyan-400 hover:text-cyan-300 flex items-center gap-1">
                <Plus size={12} /> Adicionar
              </button>
            </div>
            <div className="space-y-2">
              {form.features.map((feat, i) => (
                <div key={i} className="flex gap-2 items-center">
                  <GripVertical size={14} className="text-slate-600 shrink-0" />
                  <input
                    value={feat}
                    onChange={e => setFeature(i, e.target.value)}
                    placeholder={`Benefício ${i + 1}`}
                    className="flex-1 bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
                  />
                  <button type="button" onClick={() => removeFeature(i)}
                    className="p-1.5 rounded-lg hover:bg-rose-500/10 text-slate-500 hover:text-rose-400 transition-colors">
                    <X size={14} />
                  </button>
                </div>
              ))}
            </div>
          </div>

          {plan && (
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox" checked={form.active}
                onChange={e => setForm(f => ({ ...f, active: e.target.checked }))}
                className="accent-cyan-500"
              />
              <span className="text-sm text-slate-300">Plano ativo</span>
            </label>
          )}

          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="flex-1 py-2.5 rounded-xl border border-slate-700 text-slate-400 hover:text-white text-sm font-bold transition-colors">
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              className="flex-1 py-2.5 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-black text-sm font-black transition-colors disabled:opacity-50">
              {saving ? 'Salvando…' : 'Salvar'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── FAQ Modal ─────────────────────────────────────────────────────────────────

function FaqModal({
  clubId, faq, onClose, onSaved,
}: {
  clubId: number;
  faq: ClubFaq | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [form, setForm] = useState({
    question: faq?.question || '',
    answer: faq?.answer || '',
    sort_order: faq?.sort_order ?? 0,
    active: faq?.active ?? true,
  });
  const [saving, setSaving] = useState(false);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      if (faq) {
        await ClubService.updateFaq(faq.id, form);
      } else {
        await ClubService.createFaq({ ...form, club_id: clubId });
      }
      onSaved();
      onClose();
    } catch {
      alert('Erro ao salvar FAQ');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-lg">
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <h3 className="text-lg font-black text-white">{faq ? 'Editar FAQ' : 'Nova FAQ'}</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors"><X size={20} /></button>
        </div>
        <form onSubmit={submit} className="p-6 space-y-4">
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Pergunta *</label>
            <input
              required value={form.question}
              onChange={e => setForm(f => ({ ...f, question: e.target.value }))}
              placeholder="Ex: Como funciona o pagamento?"
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
            />
          </div>
          <div>
            <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Resposta *</label>
            <textarea
              required value={form.answer} rows={4}
              onChange={e => setForm(f => ({ ...f, answer: e.target.value }))}
              placeholder="Resposta detalhada..."
              className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 resize-none"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Ordem</label>
              <input
                type="number" min={0} value={form.sort_order}
                onChange={e => setForm(f => ({ ...f, sort_order: Number(e.target.value) }))}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
              />
            </div>
            <div className="flex items-end pb-2">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox" checked={form.active}
                  onChange={e => setForm(f => ({ ...f, active: e.target.checked }))}
                  className="accent-cyan-500"
                />
                <span className="text-sm text-slate-300">Ativo</span>
              </label>
            </div>
          </div>
          <div className="flex gap-3 pt-2">
            <button type="button" onClick={onClose}
              className="flex-1 py-2.5 rounded-xl border border-slate-700 text-slate-400 hover:text-white text-sm font-bold transition-colors">
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              className="flex-1 py-2.5 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-black text-sm font-black transition-colors disabled:opacity-50">
              {saving ? 'Salvando…' : 'Salvar'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Member Action Menu ────────────────────────────────────────────────────────

function MemberActions({ member, onChanged }: { member: ClubMember; onChanged: () => void }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  async function setStatus(status: string) {
    setOpen(false);
    setLoading(true);
    try {
      await ClubService.updateMemberStatus(member.id, status);
      onChanged();
    } catch {
      alert('Erro ao atualizar status');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="relative">
      <button
        disabled={loading}
        onClick={() => setOpen(o => !o)}
        className="text-xs font-bold px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 flex items-center gap-1 transition-colors disabled:opacity-50"
      >
        Ações <ChevronDown size={12} />
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-1 bg-slate-800 border border-slate-700 rounded-xl shadow-xl z-10 min-w-[160px] overflow-hidden">
          {member.status !== 'active' && (
            <button onClick={() => setStatus('active')}
              className="w-full text-left px-4 py-2.5 text-sm text-emerald-400 hover:bg-slate-700 flex items-center gap-2">
              <CheckCircle size={14} /> Ativar
            </button>
          )}
          {member.status === 'active' && (
            <button onClick={() => setStatus('suspended')}
              className="w-full text-left px-4 py-2.5 text-sm text-amber-400 hover:bg-slate-700 flex items-center gap-2">
              <PauseCircle size={14} /> Suspender
            </button>
          )}
          {member.status !== 'canceled' && (
            <button onClick={() => { if (confirm('Cancelar assinatura deste membro?')) setStatus('canceled'); }}
              className="w-full text-left px-4 py-2.5 text-sm text-rose-400 hover:bg-slate-700 flex items-center gap-2">
              <XCircle size={14} /> Cancelar
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// ── Main Component ────────────────────────────────────────────────────────────

type TabId = 'members' | 'partners' | 'plans' | 'content' | 'faq';

const TABS: { id: TabId; label: string; icon: any }[] = [
  { id: 'members',  label: 'Membros',           icon: Users      },
  { id: 'partners', label: 'Parceiros',          icon: Tag        },
  { id: 'plans',    label: 'Planos & Preços',    icon: DollarSign },
  { id: 'content',  label: 'Condições & Regras', icon: FileText   },
  { id: 'faq',      label: 'FAQ / Sanfona',      icon: HelpCircle },
];

export default function ClubPage({ clubId, clubName, clubSlug, accentColor }: Props) {
  const [members, setMembers]   = useState<ClubMember[]>([]);
  const [partners, setPartners] = useState<ClubPartner[]>([]);
  const [plans, setPlans]       = useState<ClubPlan[]>([]);
  const [faqs, setFaqs]         = useState<ClubFaq[]>([]);
  const [content, setContent]   = useState({ conditions: '', rules: '' });
  const [contentSaving, setContentSaving] = useState(false);
  const [contentMsg, setContentMsg]       = useState('');

  const [statusFilter, setStatusFilter] = useState('');
  const [tab, setTab]           = useState<TabId>('members');
  const [partnerModal, setPartnerModal] = useState<ClubPartner | null | 'new'>(null);
  const [planModal, setPlanModal]       = useState<ClubPlan | null | 'new'>(null);
  const [faqModal, setFaqModal]         = useState<ClubFaq | null | 'new'>(null);
  const [loading, setLoading]   = useState(true);

  const accent = accentColor;

  const loadMembers = useCallback(async () => {
    setLoading(true);
    try {
      const data = await ClubService.listMembers(clubId, { status: statusFilter || undefined, limit: 200 });
      setMembers(data || []);
    } catch {
      setMembers([]);
    } finally {
      setLoading(false);
    }
  }, [clubId, statusFilter]);

  const loadPartners = useCallback(async () => {
    try {
      const data = await ClubService.listPartners(clubId);
      setPartners(data || []);
    } catch {
      setPartners([]);
    }
  }, [clubId]);

  const loadPlans = useCallback(async () => {
    try {
      const data = await ClubService.listPlans(clubId);
      setPlans(data || []);
    } catch {
      setPlans([]);
    }
  }, [clubId]);

  const loadFaqs = useCallback(async () => {
    try {
      const data = await ClubService.listFaqs(clubId);
      setFaqs(data || []);
    } catch {
      setFaqs([]);
    }
  }, [clubId]);

  useEffect(() => { loadMembers(); }, [loadMembers]);
  useEffect(() => { loadPartners(); }, [loadPartners]);
  useEffect(() => { loadPlans(); }, [loadPlans]);
  useEffect(() => { loadFaqs(); }, [loadFaqs]);

  // Carrega conditions/rules via API pública (slug disponível como prop)
  useEffect(() => {
    if (!clubSlug) return;
    fetch(`/api/clubs/${clubSlug}`)
      .then(r => r.json())
      .then(data => {
        setContent({
          conditions: data.conditions || '',
          rules: data.rules || '',
        });
      })
      .catch(() => {});
  }, [clubSlug]);

  // KPIs
  const active     = members.filter(m => m.status === 'active').length;
  const suspended  = members.filter(m => m.status === 'suspended').length;
  const pending    = members.filter(m => m.status === 'pending_payment').length;
  const mrr        = members.filter(m => m.status === 'active').reduce((s, m) => s + Number(m.price_monthly), 0);

  // Evolution chart
  const evolutionData = (() => {
    const now = new Date();
    return Array.from({ length: 6 }, (_, i) => {
      const d = new Date(now.getFullYear(), now.getMonth() - (5 - i), 1);
      const label = d.toLocaleDateString('pt-BR', { month: 'short', year: '2-digit' });
      const count = members.filter(m => {
        const s = new Date(m.started_at);
        return s <= new Date(d.getFullYear(), d.getMonth() + 1, 0);
      }).length;
      return { label, count };
    });
  })();

  const filteredMembers = statusFilter
    ? members.filter(m => m.status === statusFilter)
    : members;

  async function deletePartner(id: number) {
    if (!confirm('Desativar este parceiro?')) return;
    await ClubService.deletePartner(id);
    loadPartners();
  }

  async function deletePlan(id: number) {
    if (!confirm('Excluir este plano?')) return;
    try {
      await ClubService.deletePlan(id);
      loadPlans();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Erro ao excluir plano');
    }
  }

  async function deleteFaq(id: number) {
    if (!confirm('Excluir esta FAQ?')) return;
    await ClubService.deleteFaq(id);
    loadFaqs();
  }

  async function saveContent(e: React.FormEvent) {
    e.preventDefault();
    setContentSaving(true);
    setContentMsg('');
    try {
      await ClubService.saveContent(clubId, content);
      setContentMsg('Salvo com sucesso!');
      setTimeout(() => setContentMsg(''), 3000);
    } catch {
      setContentMsg('Erro ao salvar.');
    } finally {
      setContentSaving(false);
    }
  }

  async function moveFaq(faq: ClubFaq, direction: 'up' | 'down') {
    const idx = faqs.indexOf(faq);
    const newIdx = direction === 'up' ? idx - 1 : idx + 1;
    if (newIdx < 0 || newIdx >= faqs.length) return;
    const neighbor = faqs[newIdx];
    await Promise.all([
      ClubService.updateFaq(faq.id, { ...faq, sort_order: neighbor.sort_order }),
      ClubService.updateFaq(neighbor.id, { ...neighbor, sort_order: faq.sort_order }),
    ]);
    loadFaqs();
  }

  return (
    <div className="space-y-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      {/* Header */}
      <header>
        <h2 className="text-4xl font-black text-white tracking-tighter">{clubName}</h2>
        <p className="text-slate-400 mt-1">Gestão de membros, planos, parceiros e conteúdo.</p>
      </header>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: 'Membros Ativos', value: active, icon: Users, color: 'emerald' },
          { label: 'MRR',  value: fmtCurrency(mrr), icon: DollarSign, color: accent },
          { label: 'Inadimplentes', value: suspended, icon: AlertTriangle, color: 'amber' },
          { label: 'Aguard. Pgto', value: pending, icon: PauseCircle, color: 'slate' },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-slate-900/40 border border-slate-800 rounded-3xl p-6 hover:border-slate-700 transition-all">
            <div className={`p-3 rounded-2xl bg-slate-800 border border-white/5 text-${color}-400 w-fit mb-4`}>
              <Icon size={22} />
            </div>
            <p className="text-slate-500 text-xs font-bold uppercase tracking-widest mb-1">{label}</p>
            <h3 className="text-3xl font-black text-white tabular-nums tracking-tighter">{value}</h3>
          </div>
        ))}
      </div>

      {/* Evolution Chart */}
      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl p-8">
        <h3 className="text-base font-black text-white uppercase tracking-wider mb-6">Evolução de Membros (6 meses)</h3>
        <div className="h-48">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={evolutionData}>
              <defs>
                <linearGradient id="gradClub" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#06b6d4" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="#06b6d4" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="label" stroke="#475569" tick={{ fontSize: 11 }} />
              <YAxis stroke="#475569" tick={{ fontSize: 11 }} allowDecimals={false} />
              <Tooltip
                contentStyle={{ background: '#0f172a', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '12px', color: '#f1f5f9', fontSize: '12px' }}
                formatter={(v: any) => [v, 'Membros']}
              />
              <Area type="monotone" dataKey="count" stroke="#06b6d4" strokeWidth={2} fill="url(#gradClub)" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-slate-800 overflow-x-auto">
        {TABS.map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            onClick={() => setTab(id)}
            className={`flex items-center gap-2 px-4 py-3 text-xs font-black uppercase tracking-wider border-b-2 whitespace-nowrap transition-all ${
              tab === id
                ? 'border-cyan-400 text-cyan-400'
                : 'border-transparent text-slate-500 hover:text-slate-300'
            }`}
          >
            <Icon size={14} /> {label}
          </button>
        ))}
      </div>

      {/* ── Members Tab ── */}
      {tab === 'members' && (
        <div className="space-y-4">
          <div className="flex gap-2 flex-wrap">
            {['', 'active', 'suspended', 'pending_payment', 'canceled'].map(s => (
              <button
                key={s}
                onClick={() => setStatusFilter(s)}
                className={`px-4 py-2 rounded-xl text-xs font-black uppercase tracking-wider border transition-all ${
                  statusFilter === s
                    ? 'bg-cyan-500/10 border-cyan-500/30 text-cyan-400'
                    : 'border-slate-700 text-slate-500 hover:text-slate-300'
                }`}
              >
                {s ? STATUS_LABEL[s] : 'Todos'}
              </button>
            ))}
          </div>

          {loading ? (
            <div className="flex justify-center py-16">
              <div className="w-8 h-8 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin" />
            </div>
          ) : (
            <div className="bg-slate-900/40 border border-slate-800 rounded-3xl overflow-hidden overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-slate-800">
                    {['Nome', 'CPF', 'Plano', 'Próx. Cobrança', 'Início', 'Status', ''].map(h => (
                      <th key={h} className="text-left px-5 py-4 text-[10px] font-black uppercase tracking-widest text-slate-500 whitespace-nowrap">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {filteredMembers.length === 0 && (
                    <tr><td colSpan={7} className="text-center py-12 text-slate-600 italic">Nenhum membro encontrado</td></tr>
                  )}
                  {filteredMembers.map(m => (
                    <tr key={m.id} className="border-b border-slate-800/50 hover:bg-slate-800/30 transition-colors">
                      <td className="px-5 py-3.5 font-semibold text-white whitespace-nowrap">{m.user_nome}</td>
                      <td className="px-5 py-3.5 text-slate-400 font-mono text-xs">{fmtCpf(m.user_cpf)}</td>
                      <td className="px-5 py-3.5 text-slate-300 whitespace-nowrap">{m.plan_name}</td>
                      <td className="px-5 py-3.5 text-slate-400 whitespace-nowrap">{fmtDate(m.next_billing_at)}</td>
                      <td className="px-5 py-3.5 text-slate-400 whitespace-nowrap">{fmtDate(m.started_at)}</td>
                      <td className="px-5 py-3.5"><StatusBadge status={m.status} /></td>
                      <td className="px-5 py-3.5">
                        <MemberActions member={m} onChanged={loadMembers} />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* ── Partners Tab ── */}
      {tab === 'partners' && (
        <div className="space-y-4">
          <div className="flex justify-end">
            <button
              onClick={() => setPartnerModal('new')}
              className="flex items-center gap-2 px-5 py-2.5 bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm rounded-xl transition-colors"
            >
              <Plus size={16} /> Novo Parceiro
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            {partners.length === 0 && (
              <p className="text-slate-600 italic col-span-3 py-8 text-center">Nenhum parceiro cadastrado</p>
            )}
            {partners.map(p => (
              <div key={p.id} className="bg-slate-900/40 border border-slate-800 rounded-2xl p-5 hover:border-slate-700 transition-all">
                <div className="flex items-start justify-between gap-2 mb-2">
                  <div>
                    <h4 className="font-black text-white">{p.name}</h4>
                    {p.specialty && <p className="text-xs text-slate-400 mt-0.5">{p.specialty}</p>}
                  </div>
                  <div className="flex gap-1">
                    <button onClick={() => setPartnerModal(p)} className="p-1.5 rounded-lg hover:bg-slate-700 text-slate-400 hover:text-white transition-colors">
                      <Edit2 size={14} />
                    </button>
                    <button onClick={() => deletePartner(p.id)} className="p-1.5 rounded-lg hover:bg-rose-500/10 text-slate-400 hover:text-rose-400 transition-colors">
                      <Trash2 size={14} />
                    </button>
                  </div>
                </div>
                {p.discount_percent > 0 && (
                  <span className="text-xs font-black text-cyan-400 bg-cyan-500/10 border border-cyan-500/20 px-2 py-0.5 rounded">
                    {p.discount_percent}% desconto
                  </span>
                )}
                {p.phone && <p className="text-xs text-slate-500 mt-2">{p.phone}</p>}
                {p.address && <p className="text-xs text-slate-500">{p.address}</p>}
                {p.notes && <p className="text-xs text-slate-600 mt-2 italic">{p.notes}</p>}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Plans Tab ── */}
      {tab === 'plans' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <p className="text-slate-400 text-sm">Planos disponíveis para assinatura neste clube.</p>
            <button
              onClick={() => setPlanModal('new')}
              className="flex items-center gap-2 px-5 py-2.5 bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm rounded-xl transition-colors"
            >
              <Plus size={16} /> Novo Plano
            </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
            {plans.length === 0 && (
              <p className="text-slate-600 italic col-span-3 py-8 text-center">Nenhum plano cadastrado</p>
            )}
            {plans.map(p => (
              <div key={p.id} className={`relative bg-slate-900/40 border rounded-3xl p-6 hover:border-slate-700 transition-all ${p.active ? 'border-slate-800' : 'border-slate-800/40 opacity-60'}`}>
                {!p.active && (
                  <span className="absolute top-3 right-3 text-[10px] font-black px-2 py-0.5 rounded bg-slate-700 text-slate-400">INATIVO</span>
                )}
                <div className="flex items-start justify-between gap-2 mb-3">
                  <div>
                    <h4 className="font-black text-white text-lg">{p.name}</h4>
                    {p.description && <p className="text-xs text-slate-500 mt-0.5">{p.description}</p>}
                  </div>
                  <div className="flex gap-1 shrink-0">
                    <button onClick={() => setPlanModal(p)} className="p-1.5 rounded-lg hover:bg-slate-700 text-slate-400 hover:text-white transition-colors">
                      <Edit2 size={14} />
                    </button>
                    <button onClick={() => deletePlan(p.id)} className="p-1.5 rounded-lg hover:bg-rose-500/10 text-slate-400 hover:text-rose-400 transition-colors">
                      <Trash2 size={14} />
                    </button>
                  </div>
                </div>

                <p className="text-3xl font-black text-cyan-400 mb-1">
                  {fmtCurrency(p.price_monthly)}
                  <span className="text-sm text-slate-500 font-medium">/mês</span>
                </p>
                {p.max_dependents > 0 && (
                  <p className="text-xs text-slate-500 mb-3">Até {p.max_dependents} dependente(s)</p>
                )}

                {p.features?.length > 0 && (
                  <ul className="space-y-1.5 mt-3 pt-3 border-t border-slate-800">
                    {p.features.map((f, i) => (
                      <li key={i} className="flex items-center gap-2 text-xs text-slate-300">
                        <CheckCircle size={12} className="text-emerald-400 shrink-0" /> {f}
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Content Tab ── */}
      {tab === 'content' && (
        <form onSubmit={saveContent} className="space-y-6 max-w-3xl">
          <p className="text-slate-400 text-sm">
            Defina as condições de adesão e regras de uso específicas para <strong className="text-white">{clubName}</strong>.
            O conteúdo é exibido na página pública do clube.
          </p>

          <div>
            <label className="text-xs font-black text-slate-400 uppercase tracking-wider block mb-2">
              Condições de Adesão
            </label>
            <textarea
              rows={8}
              value={content.conditions}
              onChange={e => setContent(c => ({ ...c, conditions: e.target.value }))}
              placeholder="Descreva as condições para adesão ao clube..."
              className="w-full bg-slate-900 border border-slate-800 rounded-2xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 resize-y"
            />
          </div>

          <div>
            <label className="text-xs font-black text-slate-400 uppercase tracking-wider block mb-2">
              Regras de Uso
            </label>
            <textarea
              rows={8}
              value={content.rules}
              onChange={e => setContent(c => ({ ...c, rules: e.target.value }))}
              placeholder="Descreva as regras de utilização do clube..."
              className="w-full bg-slate-900 border border-slate-800 rounded-2xl px-4 py-3 text-sm text-white focus:outline-none focus:border-cyan-500 resize-y"
            />
          </div>

          {/* Preview */}
          {(content.conditions || content.rules) && (
            <div className="bg-slate-900/40 border border-slate-800 rounded-2xl p-5 space-y-4">
              <p className="text-xs font-black text-slate-500 uppercase tracking-wider">Pré-visualização</p>
              {content.conditions && (
                <div>
                  <h4 className="text-sm font-black text-white mb-1">Condições de Adesão</h4>
                  <p className="text-slate-400 text-xs whitespace-pre-line">{content.conditions}</p>
                </div>
              )}
              {content.rules && (
                <div>
                  <h4 className="text-sm font-black text-white mb-1">Regras de Uso</h4>
                  <p className="text-slate-400 text-xs whitespace-pre-line">{content.rules}</p>
                </div>
              )}
            </div>
          )}

          <div className="flex items-center gap-4">
            <button
              type="submit"
              disabled={contentSaving}
              className="px-8 py-3 bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm rounded-xl transition-colors disabled:opacity-50"
            >
              {contentSaving ? 'Salvando…' : 'Salvar Conteúdo'}
            </button>
            {contentMsg && (
              <p className={`text-sm font-bold ${contentMsg.includes('sucesso') ? 'text-emerald-400' : 'text-rose-400'}`}>
                {contentMsg}
              </p>
            )}
          </div>
        </form>
      )}

      {/* ── FAQ Tab ── */}
      {tab === 'faq' && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <p className="text-slate-400 text-sm">Perguntas e respostas exibidas na página pública ({faqs.length} FAQ{faqs.length !== 1 ? 's' : ''}).</p>
            <button
              onClick={() => setFaqModal('new')}
              className="flex items-center gap-2 px-5 py-2.5 bg-cyan-500 hover:bg-cyan-400 text-black font-black text-sm rounded-xl transition-colors"
            >
              <Plus size={16} /> Nova FAQ
            </button>
          </div>

          <div className="space-y-3">
            {faqs.length === 0 && (
              <p className="text-slate-600 italic py-8 text-center">Nenhuma FAQ cadastrada</p>
            )}
            {faqs.map((f, i) => (
              <div key={f.id} className={`bg-slate-900/40 border rounded-2xl p-5 transition-all ${f.active ? 'border-slate-800' : 'border-slate-800/40 opacity-60'}`}>
                <div className="flex items-start gap-3">
                  {/* Order controls */}
                  <div className="flex flex-col gap-1 mt-0.5 shrink-0">
                    <button
                      onClick={() => moveFaq(f, 'up')}
                      disabled={i === 0}
                      className="text-slate-600 hover:text-slate-300 disabled:opacity-20 transition-colors"
                    >
                      ▲
                    </button>
                    <button
                      onClick={() => moveFaq(f, 'down')}
                      disabled={i === faqs.length - 1}
                      className="text-slate-600 hover:text-slate-300 disabled:opacity-20 transition-colors"
                    >
                      ▼
                    </button>
                  </div>

                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-2">
                      <p className="font-bold text-white text-sm">{f.question}</p>
                      <div className="flex items-center gap-1 shrink-0">
                        {f.active
                          ? <ToggleRight size={18} className="text-emerald-400" />
                          : <ToggleLeft size={18} className="text-slate-600" />
                        }
                        <button onClick={() => setFaqModal(f)} className="p-1.5 rounded-lg hover:bg-slate-700 text-slate-400 hover:text-white transition-colors">
                          <Edit2 size={14} />
                        </button>
                        <button onClick={() => deleteFaq(f.id)} className="p-1.5 rounded-lg hover:bg-rose-500/10 text-slate-400 hover:text-rose-400 transition-colors">
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </div>
                    <p className="text-slate-400 text-xs mt-1 line-clamp-2">{f.answer}</p>
                    <p className="text-slate-700 text-[10px] mt-2">Ordem: {f.sort_order}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Modals */}
      {partnerModal !== null && (
        <PartnerModal
          clubId={clubId}
          partner={partnerModal === 'new' ? null : partnerModal}
          onClose={() => setPartnerModal(null)}
          onSaved={loadPartners}
        />
      )}
      {planModal !== null && (
        <PlanModal
          clubId={clubId}
          plan={planModal === 'new' ? null : planModal}
          onClose={() => setPlanModal(null)}
          onSaved={loadPlans}
        />
      )}
      {faqModal !== null && (
        <FaqModal
          clubId={clubId}
          faq={faqModal === 'new' ? null : faqModal}
          onClose={() => setFaqModal(null)}
          onSaved={loadFaqs}
        />
      )}
    </div>
  );
}
