import { useState, useEffect } from 'react'
import { X, Eye, EyeOff, ChevronRight, ChevronLeft, Check, User, Mail, Lock } from 'lucide-react'
import { AuthAPI } from '../api'
import { useTenantCtx } from '../context/TenantContext'

interface Props {
  onSuccess: (user: any) => void
  onClose?: () => void
  inline?: boolean
  defaultTab?: 'login' | 'register'
}

function maskCpf(v: string) {
  return v.replace(/\D/g, '').slice(0, 11)
    .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, '').slice(0, 11)
    .replace(/^(\d{2})(\d)/, '($1) $2')
    .replace(/(\d{5})(\d)/, '$1-$2')
}

// ─── Step indicators ──────────────────────────────────────────────────────────

const STEPS = [
  { label: 'Identidade', icon: User },
  { label: 'Contato',    icon: Mail },
  { label: 'Segurança',  icon: Lock },
]

function StepIndicator({ current }: { current: number }) {
  return (
    <div className="flex items-center justify-center gap-0 mb-6">
      {STEPS.map((s, i) => {
        const done    = i < current
        const active  = i === current
        const Icon    = s.icon
        return (
          <div key={i} className="flex items-center">
            {/* Circle */}
            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-black shrink-0 transition-all duration-300 ${
              done   ? 'bg-emerald-500 text-white' :
              active ? 'bg-amber-500 text-black ring-4 ring-amber-500/20' :
                       'bg-slate-800 text-slate-500'
            }`}>
              {done ? <Check size={13} /> : <Icon size={13} />}
            </div>
            {/* Connector */}
            {i < STEPS.length - 1 && (
              <div className={`h-0.5 w-8 transition-all duration-500 ${i < current ? 'bg-emerald-500' : 'bg-slate-700'}`} />
            )}
          </div>
        )
      })}
    </div>
  )
}

// ─── Animated slide container ─────────────────────────────────────────────────

function SlidePanel({ children, dir }: { children: React.ReactNode; dir: 'left' | 'right' | null }) {
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    // Tiny delay so the initial transform is applied before transition kicks in
    const t = requestAnimationFrame(() => setVisible(true))
    return () => cancelAnimationFrame(t)
  }, [])

  const from = dir === 'right' ? 'translateX(60px)' : dir === 'left' ? 'translateX(-60px)' : 'translateX(0)'

  return (
    <div
      style={{
        transform:  visible ? 'translateX(0)' : from,
        opacity:    visible ? 1 : 0,
        transition: 'transform 0.28s cubic-bezier(.4,0,.2,1), opacity 0.28s ease',
      }}
    >
      {children}
    </div>
  )
}

// ─── Field component ──────────────────────────────────────────────────────────

function Field({
  label, type = 'text', value, onChange, required, autoFocus, placeholder, minLength,
  suffix,
}: {
  label: string
  type?: string
  value: string
  onChange: (v: string) => void
  required?: boolean
  autoFocus?: boolean
  placeholder?: string
  minLength?: number
  suffix?: React.ReactNode
}) {
  return (
    <div>
      <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">
        {label}{required && ' *'}
      </label>
      <div className="relative mt-1">
        <input
          type={type}
          required={required}
          autoFocus={autoFocus}
          value={value}
          minLength={minLength}
          placeholder={placeholder}
          onChange={e => onChange(e.target.value)}
          className="w-full bg-slate-800 border border-slate-700 rounded-xl px-4 py-2.5 pr-10 text-sm text-white focus:outline-none focus:border-amber-500 transition-colors"
        />
        {suffix && (
          <div className="absolute right-3 top-1/2 -translate-y-1/2">{suffix}</div>
        )}
      </div>
    </div>
  )
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function AuthModal({ onSuccess, onClose, inline, defaultTab = 'login' }: Props) {
  const [tab, setTab]           = useState<'login' | 'register'>(defaultTab)
  const [showPass, setShowPass] = useState(false)
  const [showConfirm, setShowConfirm] = useState(false)
  const [loading, setLoading]   = useState(false)
  const [err, setErr]           = useState('')
  const tenant                  = useTenantCtx()

  // Login
  const [loginForm, setLoginForm] = useState({ email: '', password: '' })

  // Forgot
  const [forgotMode, setForgotMode] = useState(false)
  const [forgotEmail, setForgotEmail] = useState('')
  const [forgotSent, setForgotSent]   = useState(false)

  // Register wizard
  const [step, setStep]   = useState(0)
  const [dir, setDir]     = useState<'left' | 'right'>('right')
  const [stepKey, setStepKey] = useState(0)   // force remount to trigger slide animation
  const [regDone, setRegDone] = useState(false)

  const [regForm, setRegForm] = useState({
    nome: '', cpf: '', email: '', telefone: '', password: '', confirm: '',
  })

  function setReg(key: keyof typeof regForm, val: string) {
    setRegForm(f => ({ ...f, [key]: val }))
  }

  // ── Navigation ──────────────────────────────────────────────────────────────

  function goNext() {
    setErr('')
    if (!validateStep()) return
    setDir('right')
    setStep(s => s + 1)
    setStepKey(k => k + 1)
  }

  function goBack() {
    setErr('')
    setDir('left')
    setStep(s => s - 1)
    setStepKey(k => k + 1)
  }

  function validateStep(): boolean {
    if (step === 0) {
      if (!regForm.nome.trim())         { setErr('Informe seu nome completo');      return false }
      if (regForm.cpf.replace(/\D/g,'').length < 11) { setErr('CPF inválido'); return false }
    }
    if (step === 1) {
      if (!regForm.email.includes('@')) { setErr('Email inválido');                 return false }
      if (regForm.telefone.replace(/\D/g,'').length < 10) { setErr('Telefone inválido'); return false }
    }
    if (step === 2) {
      if (regForm.password.length < 6)  { setErr('Senha deve ter ao menos 6 caracteres'); return false }
      if (regForm.password !== regForm.confirm) { setErr('As senhas não coincidem'); return false }
    }
    return true
  }

  // ── Handlers ────────────────────────────────────────────────────────────────

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault(); setLoading(true); setErr('')
    try {
      const data = await AuthAPI.login(loginForm.email, loginForm.password)
      let u: any = data?.user || data
      if (!u || !u.nome) {
        try { u = await AuthAPI.getMe() } catch { /* mantém o que tiver */ }
      }
      onSuccess(u)
    } catch (ex: any) {
      setErr(ex.response?.data?.error || 'Credenciais inválidas')
    } finally { setLoading(false) }
  }

  async function handleRegister() {
    if (!validateStep()) return
    setLoading(true); setErr('')
    try {
      const data = await AuthAPI.register({
        nome: regForm.nome, email: regForm.email,
        cpf: regForm.cpf, telefone: regForm.telefone, password: regForm.password,
      })
      setRegDone(true)
      setTimeout(() => onSuccess(data.user || data), 1200)
    } catch (ex: any) {
      setErr(ex.response?.data?.error || 'Erro ao criar conta')
    } finally { setLoading(false) }
  }

  async function handleForgot(e: React.FormEvent) {
    e.preventDefault(); setLoading(true); setErr('')
    try {
      await AuthAPI.forgotPassword(forgotEmail)
      setForgotSent(true)
    } catch (ex: any) {
      setErr(ex.response?.data?.error || 'Erro ao enviar link')
    } finally { setLoading(false) }
  }

  // ── Reset wizard when switching tabs ────────────────────────────────────────

  function switchTab(t: 'login' | 'register') {
    setTab(t); setErr('')
    setStep(0); setStepKey(0); setDir('right'); setRegDone(false)
  }

  // ── Step content ─────────────────────────────────────────────────────────────

  const eyeToggle = (show: boolean, toggle: () => void) => (
    <button type="button" onClick={toggle} className="text-slate-500 hover:text-slate-300 transition-colors">
      {show ? <EyeOff size={16} /> : <Eye size={16} />}
    </button>
  )

  function renderStep() {
    if (regDone) {
      return (
        <div className="flex flex-col items-center justify-center py-6 gap-3">
          <div className="w-14 h-14 rounded-full bg-emerald-500/20 flex items-center justify-center">
            <Check size={28} className="text-emerald-400" />
          </div>
          <p className="text-white font-black text-lg">Conta criada!</p>
          <p className="text-slate-400 text-sm text-center">Você será redirecionado em instantes…</p>
        </div>
      )
    }

    if (step === 0) return (
      <div className="space-y-4">
        <Field label="Nome completo" value={regForm.nome} onChange={v => setReg('nome', v)} required autoFocus />
        <Field label="CPF" value={regForm.cpf} placeholder="000.000.000-00"
          onChange={v => setReg('cpf', maskCpf(v))} required />
      </div>
    )

    if (step === 1) return (
      <div className="space-y-4">
        <Field label="Email" type="email" value={regForm.email} placeholder="seu@email.com"
          onChange={v => setReg('email', v)} required autoFocus />
        <Field label="Telefone" type="tel" value={regForm.telefone} placeholder="(00) 00000-0000"
          onChange={v => setReg('telefone', maskPhone(v))} required />
      </div>
    )

    if (step === 2) return (
      <div className="space-y-4">
        <Field label="Senha" type={showPass ? 'text' : 'password'} value={regForm.password}
          onChange={v => setReg('password', v)} required autoFocus minLength={6}
          suffix={eyeToggle(showPass, () => setShowPass(s => !s))} />
        <Field label="Confirmar senha" type={showConfirm ? 'text' : 'password'} value={regForm.confirm}
          onChange={v => setReg('confirm', v)} required
          suffix={eyeToggle(showConfirm, () => setShowConfirm(s => !s))} />
      </div>
    )

    return null
  }

  // ── Inner markup ─────────────────────────────────────────────────────────────

  const isLastStep = step === STEPS.length - 1

  const inner = (
    <div className={inline ? '' : 'bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-md'}>
      {/* Header */}
      {!inline && (
        <div className="flex items-center justify-between px-6 pt-6 pb-4 border-b border-slate-800">
          <h3 className="text-lg font-black text-white">
            {forgotMode ? 'Recuperar Senha' : tab === 'login' ? 'Entrar' : 'Criar conta'}
          </h3>
          {onClose && (
            <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors">
              <X size={20} />
            </button>
          )}
        </div>
      )}

      <div className="p-6 space-y-4">
        {/* Tabs */}
        {!forgotMode && (
          <div className="flex gap-1 bg-slate-800 rounded-xl p-1">
            {(['login', 'register'] as const).map(t => (
              <button key={t} onClick={() => switchTab(t)}
                className={`flex-1 py-2 rounded-lg text-sm font-black transition-all ${
                  tab === t ? 'bg-slate-700 text-white shadow' : 'text-slate-500 hover:text-slate-300'
                }`}>
                {t === 'login' ? 'Entrar' : 'Cadastrar'}
              </button>
            ))}
          </div>
        )}

        {/* Error banner */}
        {err && (
          <p className="text-rose-400 text-sm font-medium bg-rose-500/10 border border-rose-500/20 rounded-xl px-4 py-2">
            {err}
          </p>
        )}

        {/* ── Forgot password ── */}
        {forgotMode && (
          forgotSent ? (
            <div className="text-center py-4 space-y-2">
              <p className="text-emerald-400 font-bold">Link enviado!</p>
              <p className="text-slate-400 text-sm">Verifique seu WhatsApp para redefinir a senha.</p>
              <button onClick={() => { setForgotMode(false); setForgotSent(false) }}
                className="mt-3 text-sm text-slate-400 hover:text-white underline">
                Voltar ao login
              </button>
            </div>
          ) : (
            <form onSubmit={handleForgot} className="space-y-4">
              <Field label="Email" type="email" value={forgotEmail} placeholder="seu@email.com"
                onChange={setForgotEmail} required />
              <button type="submit" disabled={loading}
                className="w-full py-3 rounded-xl font-black text-sm text-black transition-colors disabled:opacity-50"
                style={{ background: tenant.primary_color }}>
                {loading ? 'Enviando…' : 'Enviar link de recuperação'}
              </button>
              <button type="button" onClick={() => setForgotMode(false)}
                className="w-full text-slate-500 hover:text-white text-sm transition-colors">
                Voltar
              </button>
            </form>
          )
        )}

        {/* ── Login ── */}
        {!forgotMode && tab === 'login' && (
          <form onSubmit={handleLogin} className="space-y-4">
            <Field label="Email" type="email" value={loginForm.email} placeholder="seu@email.com"
              onChange={v => setLoginForm(f => ({ ...f, email: v }))} required autoFocus />
            <Field label="Senha" type={showPass ? 'text' : 'password'} value={loginForm.password}
              onChange={v => setLoginForm(f => ({ ...f, password: v }))} required
              suffix={eyeToggle(showPass, () => setShowPass(s => !s))} />
            <button type="submit" disabled={loading}
              className="w-full py-3 rounded-xl font-black text-sm text-black transition-colors disabled:opacity-50"
              style={{ background: tenant.primary_color }}>
              {loading ? 'Entrando…' : 'Entrar'}
            </button>
            <button type="button" onClick={() => { setForgotMode(true); setErr('') }}
              className="w-full text-center text-xs text-slate-500 hover:text-slate-300 transition-colors">
              Esqueci minha senha
            </button>
          </form>
        )}

        {/* ── Register wizard ── */}
        {!forgotMode && tab === 'register' && (
          <div>
            <StepIndicator current={step} />

            {/* Step label */}
            {!regDone && (
              <p className="text-center text-xs font-bold text-slate-500 uppercase tracking-widest mb-4">
                {STEPS[step]?.label}
              </p>
            )}

            {/* Animated step content */}
            <div className="overflow-hidden">
              <SlidePanel key={stepKey} dir={dir}>
                {renderStep()}
              </SlidePanel>
            </div>

            {/* Navigation buttons */}
            {!regDone && (
              <div className="flex gap-2 mt-6">
                {step > 0 && (
                  <button type="button" onClick={goBack}
                    className="flex items-center gap-1 px-4 py-2.5 rounded-xl text-sm font-bold text-slate-400 hover:text-white bg-slate-800 hover:bg-slate-700 transition-all">
                    <ChevronLeft size={16} /> Voltar
                  </button>
                )}
                {!isLastStep ? (
                  <button type="button" onClick={goNext}
                    className="flex-1 flex items-center justify-center gap-1 py-2.5 rounded-xl text-sm font-black text-black transition-all disabled:opacity-50"
                    style={{ background: tenant.primary_color }}>
                    Avançar <ChevronRight size={16} />
                  </button>
                ) : (
                  <button type="button" onClick={handleRegister} disabled={loading}
                    className="flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-black text-black transition-all disabled:opacity-50"
                    style={{ background: tenant.primary_color }}>
                    {loading ? 'Criando conta…' : <><Check size={15} /> Criar conta</>}
                  </button>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  )

  if (inline) return inner

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      {inner}
    </div>
  )
}
