import { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { CheckCircle, XCircle, Clock } from 'lucide-react'
import { ClubAPI } from '../api'
import { useTenantCtx } from '../context/TenantContext'

function fmtCpf(cpf: string) {
  return cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4')
}
function fmtDate(s: string | null) {
  if (!s) return '—'
  return new Date(s).toLocaleDateString('pt-BR')
}

const STATUS_ICON: Record<string, any> = {
  active: CheckCircle,
  pending_payment: Clock,
  suspended: XCircle,
}
const STATUS_COLOR: Record<string, string> = {
  active: '#10b981',
  pending_payment: '#f59e0b',
  suspended: '#ef4444',
}
const STATUS_LABEL: Record<string, string> = {
  active: 'ATIVO',
  pending_payment: 'AGUARDANDO PAGAMENTO',
  suspended: 'SUSPENSO',
}

export default function CarteirinhaPage() {
  const { cpf } = useParams<{ cpf: string }>()
  const [cards, setCards] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const tenant = useTenantCtx()

  useEffect(() => {
    if (!cpf) return
    ClubAPI.getCard(cpf)
      .then(setCards)
      .catch(() => setCards([]))
      .finally(() => setLoading(false))
  }, [cpf])

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

  if (!cards.length) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center p-4">
        <div className="text-center space-y-3">
          <XCircle size={48} className="text-slate-700 mx-auto" />
          <p className="text-slate-500">Nenhuma assinatura ativa encontrada.</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-black flex items-center justify-center p-4">
      <div className="w-full max-w-sm space-y-4">
        <div className="text-center mb-6">
          {tenant.logo_url
            ? <img src={tenant.logo_url} alt={tenant.name} className="h-10 object-contain mx-auto mb-2" />
            : <p className="font-black text-lg" style={{ color: tenant.primary_color }}>{tenant.name}</p>}
          <p className="text-slate-500 text-sm">Carteirinha Digital</p>
        </div>

        {cards.map((c, i) => {
          const StatusIcon = STATUS_ICON[c.status] || Clock
          const color = STATUS_COLOR[c.status] || '#94a3b8'

          return (
            <div key={i}
              className="relative rounded-3xl overflow-hidden border"
              style={{ borderColor: color + '30', background: `linear-gradient(135deg, ${color}08, transparent)` }}>
              {/* Header bar */}
              <div className="h-2 w-full" style={{ background: color }} />

              <div className="p-6 space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h2 className="text-xl font-black text-white">{c.club_name}</h2>
                    <p className="text-slate-500 text-sm">{c.plan_name}</p>
                  </div>
                  <div className="flex items-center gap-2" style={{ color }}>
                    <StatusIcon size={20} />
                  </div>
                </div>

                <div className="bg-black/30 rounded-2xl p-4 space-y-3">
                  <div>
                    <p className="text-slate-600 text-xs uppercase tracking-wider">Titular</p>
                    <p className="font-black text-white mt-0.5">{c.user_nome}</p>
                  </div>
                  <div>
                    <p className="text-slate-600 text-xs uppercase tracking-wider">CPF</p>
                    <p className="font-mono font-bold text-white mt-0.5">{fmtCpf(c.user_cpf)}</p>
                  </div>
                  <div className="grid grid-cols-2 gap-3 pt-1 border-t border-white/5">
                    <div>
                      <p className="text-slate-600 text-xs uppercase tracking-wider">Membro desde</p>
                      <p className="text-white text-sm font-bold mt-0.5">{fmtDate(c.started_at)}</p>
                    </div>
                    <div>
                      <p className="text-slate-600 text-xs uppercase tracking-wider">Válido até</p>
                      <p className="text-white text-sm font-bold mt-0.5">{fmtDate(c.next_billing_at)}</p>
                    </div>
                  </div>
                </div>

                <div className="flex items-center justify-center gap-2 py-2 rounded-xl border"
                  style={{ borderColor: color + '30', color }}>
                  <StatusIcon size={14} />
                  <span className="text-xs font-black uppercase tracking-wider">{STATUS_LABEL[c.status] || c.status}</span>
                </div>
              </div>
            </div>
          )
        })}

        <p className="text-center text-xs text-slate-700 mt-4">
          Apresente esta carteirinha nas clínicas parceiras
        </p>
      </div>
    </div>
  )
}
