import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { CheckCircle, ChevronDown, ChevronUp, MapPin, Phone, Percent, X } from 'lucide-react'
import { ClubAPI } from '../api'
import { useTenantCtx } from '../context/TenantContext'
import AuthModal from '../components/AuthModal'

function maskCpf(v: string) {
  return v.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2')
}
function maskPhone(v: string) {
  return v.replace(/\D/g, '').replace(/^(\d{2})(\d)/, '($1) $2').replace(/(\d{5})(\d)/, '$1-$2')
}

// ── Subscribe Modal ───────────────────────────────────────────────────────────

function SubscribeModal({
  club, plan, user, onClose, onSuccess,
}: {
  club: any; plan: any; user: any; onClose: () => void; onSuccess: () => void
}) {
  const [step, setStep]   = useState<'form' | 'auth' | 'done'>(user ? 'form' : 'form')
  const [form, setForm]   = useState({
    user_cpf: user?.cpf || '', user_nome: user?.nome || '',
    user_telefone: user?.telefone || '', user_email: user?.email || '',
  })
  const [err, setErr]     = useState('')
  const [loading, setLoading] = useState(false)
  const tenant = useTenantCtx()

  async function subscribe(e: React.FormEvent) {
    e.preventDefault(); setLoading(true); setErr('')
    try {
      await ClubAPI.subscribe(club.slug, { plan_id: plan.id, ...form })
      setStep('done')
      setTimeout(onSuccess, 2500)
    } catch (ex: any) {
      setErr(ex.response?.data?.error || 'Erro ao realizar assinatura')
    } finally { setLoading(false) }
  }

  if (step === 'done') {
    return (
      <div className="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4">
        <div className="bg-slate-900 border border-slate-800 rounded-3xl p-10 text-center max-w-sm w-full space-y-4">
          <CheckCircle size={56} className="text-emerald-400 mx-auto" />
          <h3 className="text-xl font-black text-white">Assinatura realizada!</h3>
          <p className="text-slate-400 text-sm">
            Você receberá o link de pagamento via WhatsApp em breve. Bem-vindo ao {club.name}!
          </p>
        </div>
      </div>
    )
  }

  if (step === 'auth') {
    return (
      <div className="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4">
        <div className="w-full max-w-md">
          <AuthModal
            inline={false}
            onSuccess={u => { setForm(f => ({ ...f, user_cpf: u.cpf || f.user_cpf, user_nome: u.nome || f.user_nome, user_telefone: u.telefone || f.user_telefone, user_email: u.email || f.user_email })); setStep('form') }}
            onClose={() => setStep('form')}
          />
        </div>
      </div>
    )
  }

  return (
    <div className="fixed inset-0 bg-black/70 z-50 flex items-end md:items-center justify-center p-4">
      <div className="bg-slate-900 border border-slate-800 rounded-t-3xl md:rounded-3xl w-full max-w-md max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between p-5 border-b border-slate-800">
          <div>
            <h3 className="font-black text-white">Assinar {club.name}</h3>
            <p className="text-slate-500 text-sm">{plan.name} · R$ {Number(plan.price_monthly).toFixed(2).replace('.', ',')}/mês</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors"><X size={20} /></button>
        </div>

        <form onSubmit={subscribe} className="p-5 space-y-4">
          {!user && (
            <div className="bg-slate-800/30 border border-slate-700 rounded-xl px-4 py-3 flex items-center justify-between">
              <p className="text-xs text-slate-400">Já tem conta?</p>
              <button type="button" onClick={() => setStep('auth')}
                className="text-xs font-black hover:opacity-80" style={{ color: tenant.primary_color }}>
                Entrar →
              </button>
            </div>
          )}

          {[
            { label: 'Nome completo', key: 'user_nome', type: 'text', mask: null },
            { label: 'CPF', key: 'user_cpf', type: 'text', mask: maskCpf },
            { label: 'Telefone (WhatsApp)', key: 'user_telefone', type: 'tel', mask: maskPhone },
            { label: 'Email (opcional)', key: 'user_email', type: 'email', mask: null },
          ].map(({ label, key, type, mask }) => (
            <div key={key}>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">{label}</label>
              <input type={type} required={key !== 'user_email'}
                value={(form as any)[key]}
                onChange={e => { const v = mask ? mask(e.target.value) : e.target.value; setForm(f => ({ ...f, [key]: v })) }}
                className="mt-1 w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-amber-500"
              />
            </div>
          ))}

          {err && <p className="text-rose-400 text-sm">{err}</p>}

          <button type="submit" disabled={loading}
            className="w-full py-4 rounded-2xl font-black text-black transition-all hover:opacity-90 disabled:opacity-40"
            style={{ background: tenant.primary_color }}>
            {loading ? 'Processando…' : `Assinar por R$ ${Number(plan.price_monthly).toFixed(2).replace('.', ',')}/mês`}
          </button>
        </form>
      </div>
    </div>
  )
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function ClubePage({ user }: { user?: any }) {
  const { slug }            = useParams<{ slug: string }>()
  const navigate            = useNavigate()
  const [club, setClub]     = useState<any>(null)
  const [faqs, setFaqs]     = useState<{ id: number; question: string; answer: string }[]>([])
  const [loading, setLoading] = useState(true)
  const [selPlan, setSelPlan] = useState<any>(null)
  const [openFaq, setOpenFaq] = useState<number | null>(null)
  const tenant = useTenantCtx()

  useEffect(() => {
    if (!slug) return
    Promise.all([
      ClubAPI.get(slug),
      ClubAPI.getFaqs(slug),
    ])
      .then(([clubData, faqData]) => {
        setClub(clubData)
        setFaqs(faqData || [])
      })
      .catch(() => setClub(null))
      .finally(() => setLoading(false))
  }, [slug])

  if (loading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center pt-16">
        <div className="w-8 h-8 border-2 border-t-transparent rounded-full animate-spin" style={{ borderColor: tenant.primary_color }} />
      </div>
    )
  }

  if (!club) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center pt-16">
        <p className="text-slate-600 italic">Clube não encontrado.</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-black pt-16">
      {/* Hero */}
      <section className="relative py-20 overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-slate-900 to-black" />
        <div className="absolute top-0 right-0 w-96 h-96 rounded-full blur-3xl opacity-10"
          style={{ background: tenant.primary_color }} />
        <div className="relative z-10 max-w-4xl mx-auto px-4 text-center">
          <h1 className="text-5xl font-black text-white tracking-tighter mb-4">{club.name}</h1>
          {club.description && <p className="text-slate-400 text-xl max-w-2xl mx-auto">{club.description}</p>}
        </div>
      </section>

      {/* Plans */}
      <section className="py-16 max-w-5xl mx-auto px-4">
        <h2 className="text-2xl font-black text-white text-center mb-10 tracking-tighter">Escolha seu plano</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          {(club.plans || []).map((p: any, i: number) => {
            const featured = i === 0
            return (
              <div key={p.id}
                className={`relative border rounded-3xl p-8 transition-all ${
                  featured ? 'border-transparent' : 'border-slate-800 bg-slate-900/40'
                }`}
                style={featured ? { background: 'linear-gradient(135deg, rgba(245,158,11,0.08), rgba(16,185,129,0.05))', borderColor: tenant.primary_color + '40' } : {}}>
                {featured && (
                  <span className="absolute -top-3 left-1/2 -translate-x-1/2 text-xs font-black px-4 py-1 rounded-full text-black"
                    style={{ background: tenant.primary_color }}>
                    Mais popular
                  </span>
                )}
                <h3 className="text-xl font-black text-white mb-1">{p.name}</h3>
                {p.description && <p className="text-slate-500 text-sm mb-4">{p.description}</p>}
                <p className="text-4xl font-black mb-6" style={{ color: tenant.primary_color }}>
                  R$ {Number(p.price_monthly).toFixed(2).replace('.', ',')}
                  <span className="text-base text-slate-500 font-medium">/mês</span>
                </p>
                {/* Features */}
                {Array.isArray(p.features) && (
                  <ul className="space-y-2 mb-6">
                    {p.features.map((f: string, fi: number) => (
                      <li key={fi} className="flex items-center gap-2 text-sm text-slate-300">
                        <CheckCircle size={14} className="text-emerald-400 shrink-0" /> {f}
                      </li>
                    ))}
                  </ul>
                )}
                <button
                  onClick={() => setSelPlan(p)}
                  className="w-full py-3.5 rounded-2xl font-black text-sm transition-all hover:opacity-90"
                  style={featured
                    ? { background: tenant.primary_color, color: '#000' }
                    : { background: 'rgba(255,255,255,0.05)', color: '#fff', border: '1px solid rgba(255,255,255,0.1)' }}>
                  Assinar {p.name}
                </button>
              </div>
            )
          })}
        </div>
      </section>

      {/* Partners */}
      {club.partners?.length > 0 && (
        <section className="py-16 bg-slate-950/50">
          <div className="max-w-5xl mx-auto px-4">
            <h2 className="text-2xl font-black text-white tracking-tighter mb-8 text-center">Parceiros da Rede</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
              {club.partners.map((p: any) => (
                <div key={p.id} className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-2">
                  <div className="flex items-start justify-between">
                    <div>
                      <h4 className="font-black text-white">{p.name}</h4>
                      {p.specialty && <p className="text-slate-500 text-xs">{p.specialty}</p>}
                    </div>
                    {p.discount_percent > 0 && (
                      <span className="flex items-center gap-1 text-xs font-black text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded">
                        <Percent size={10} /> {p.discount_percent}%
                      </span>
                    )}
                  </div>
                  {p.address && (
                    <p className="text-xs text-slate-600 flex items-center gap-1">
                      <MapPin size={11} /> {p.address}
                    </p>
                  )}
                  {p.phone && (
                    <p className="text-xs text-slate-600 flex items-center gap-1">
                      <Phone size={11} /> {p.phone}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Condições de Adesão */}
      {club.conditions && (
        <section className="py-16 bg-slate-950/50">
          <div className="max-w-3xl mx-auto px-4">
            <h2 className="text-2xl font-black text-white tracking-tighter mb-6 text-center">Condições de Adesão</h2>
            <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6">
              <p className="text-slate-300 text-sm whitespace-pre-line leading-relaxed">{club.conditions}</p>
            </div>
          </div>
        </section>
      )}

      {/* Regras de Uso */}
      {club.rules && (
        <section className="py-16">
          <div className="max-w-3xl mx-auto px-4">
            <h2 className="text-2xl font-black text-white tracking-tighter mb-6 text-center">Regras de Uso</h2>
            <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6">
              <p className="text-slate-300 text-sm whitespace-pre-line leading-relaxed">{club.rules}</p>
            </div>
          </div>
        </section>
      )}

      {/* FAQ */}
      {faqs.length > 0 && (
        <section className="py-16 max-w-3xl mx-auto px-4">
          <h2 className="text-2xl font-black text-white tracking-tighter mb-8 text-center">Dúvidas Frequentes</h2>
          <div className="space-y-2">
            {faqs.map((f, i) => (
              <div key={f.id} className="bg-slate-900 border border-slate-800 rounded-2xl overflow-hidden">
                <button onClick={() => setOpenFaq(openFaq === i ? null : i)}
                  className="w-full flex items-center justify-between p-5 text-left hover:bg-slate-800/50 transition-colors">
                  <span className="font-bold text-white text-sm pr-4">{f.question}</span>
                  {openFaq === i ? <ChevronUp size={16} className="text-slate-400 shrink-0" /> : <ChevronDown size={16} className="text-slate-400 shrink-0" />}
                </button>
                {openFaq === i && (
                  <div className="px-5 pb-5">
                    <p className="text-slate-400 text-sm">{f.answer}</p>
                  </div>
                )}
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Subscribe modal */}
      {selPlan && (
        <SubscribeModal
          club={club}
          plan={selPlan}
          user={user}
          onClose={() => setSelPlan(null)}
          onSuccess={() => { setSelPlan(null); navigate('/minha-area') }}
        />
      )}
    </div>
  )
}
