'use client'
import { useState } from 'react'
import PinInput from './PinInput'

interface UserData {
  id: string; name: string; phone: string; email: string; walletNGN: number
  emailVerified?: boolean; idVerified?: boolean
  virtualAccountNumber?: string; virtualAccountBank?: string; virtualAccountName?: string
}

interface Props {
  onAuth: (user: UserData) => void
  // If set, user already has a session — show PIN gate only
  existingUserId?: string
  existingUserName?: string
}

type Screen =
  | 'choice'
  // Registration flow
  | 'reg_phone' | 'reg_email' | 'reg_name' | 'reg_password' | 'reg_pin' | 'reg_verify_email'
  // Login flow
  | 'login_id' | 'login_password'
  // Pin gate (returning user)
  | 'pin_gate'
  // ID verification (post-login, Nigerian users)
  | 'id_verify'

export default function AuthGate({ onAuth, existingUserId, existingUserName }: Props) {
  const [screen, setScreen] = useState<Screen>(existingUserId ? 'pin_gate' : 'choice')

  // Registration state
  const [phone, setPhone] = useState('')
  const [email, setEmail] = useState('')
  const [name, setName] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [regUserId, setRegUserId] = useState('')

  // Login state
  const [loginId, setLoginId] = useState('')
  const [loginPassword, setLoginPassword] = useState('')
  const [showLoginPw, setShowLoginPw] = useState(false)
  const [unverifiedUserId, setUnverifiedUserId] = useState('')

  // ID verify state
  const [pendingUser, setPendingUser] = useState<UserData | null>(null)
  const [idType, setIdType] = useState<'BVN' | 'NIN'>('BVN')
  const [idNumber, setIdNumber] = useState('')

  // OTP
  const [otp, setOtp] = useState('')

  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  // ── helpers ──────────────────────────────────────────────────────────────────
  function go(s: Screen) { setError(''); setScreen(s) }

  function validatePhone(): boolean {
    if (!/^0[789]\d{9}$/.test(phone)) {
      setError('Enter a valid Nigerian number (e.g. 08012345678)'); return false
    }
    setError(''); return true
  }

  function validateEmail(): boolean {
    if (!/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i.test(email)) {
      setError('Enter a valid email address'); return false
    }
    setError(''); return true
  }

  // ── Registration ─────────────────────────────────────────────────────────────
  async function handleRegisterPin(pin: string) {
    setLoading(true); setError('')
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, email, name, password, pin }),
      })
      const data = await res.json()
      if (!res.ok) { setError(data.error); setLoading(false); return }
      setRegUserId(data.userId)
      setLoading(false)
      go('reg_verify_email')
    } catch { setError('Network error'); setLoading(false) }
  }

  async function handleVerifyEmail() {
    if (otp.trim().length !== 6) { setError('Enter the 6-digit code'); return }
    setLoading(true); setError('')
    try {
      const res = await fetch('/api/auth/verify-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: regUserId, otp: otp.trim() }),
      })
      const data = await res.json()
      if (!res.ok) { setError(data.error); setLoading(false); return }
      setLoading(false)
      // After email verify, go to ID verification
      setPendingUser(data.user)
      go('id_verify')
    } catch { setError('Network error'); setLoading(false) }
  }

  async function handleResendOTP() {
    setLoading(true); setError('')
    try {
      await fetch('/api/auth/resend-otp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: regUserId }),
      })
      setLoading(false)
      setError('New code sent! Check your email.')
    } catch { setLoading(false) }
  }

  // ── Login ─────────────────────────────────────────────────────────────────────
  async function handleLogin() {
    if (!loginId.trim() || !loginPassword) { setError('Enter your login and password'); return }
    setLoading(true); setError('')
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ identifier: loginId.trim(), password: loginPassword }),
      })
      const data = await res.json()
      if (!res.ok) {
        if (data.unverified) {
          setUnverifiedUserId(data.userId)
          setRegUserId(data.userId)
          setLoading(false)
          go('reg_verify_email')
          return
        }
        setError(data.error); setLoading(false); return
      }
      setLoading(false)
      if (!data.user.idVerified) {
        setPendingUser(data.user)
        go('id_verify')
      } else {
        onAuth(data.user)
      }
    } catch { setError('Network error'); setLoading(false) }
  }

  // ── PIN gate (returning user) ─────────────────────────────────────────────────
  async function handlePinGate(pin: string) {
    setLoading(true); setError('')
    try {
      const res = await fetch('/api/auth/verify-pin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pin }),
      })
      const data = await res.json()
      if (!res.ok) { setError(data.error); setLoading(false); return }
      setLoading(false)
      if (!data.user.idVerified) {
        setPendingUser(data.user)
        go('id_verify')
      } else {
        onAuth(data.user)
      }
    } catch { setError('Network error'); setLoading(false) }
  }

  // ── ID Verification ────────────────────────────────────────────────────────────
  async function handleIdVerify() {
    if (idNumber.length !== 11) { setError(`${idType} must be exactly 11 digits`); return }
    setLoading(true); setError('')
    try {
      const res = await fetch('/api/auth/verify-id', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ idType, idNumber }),
      })
      const data = await res.json()
      if (!res.ok) { setError(data.error); setLoading(false); return }
      setLoading(false)
      if (pendingUser) onAuth({ ...pendingUser, idVerified: true })
    } catch { setError('Network error'); setLoading(false) }
  }

  function skipIdVerify() {
    // Allow skipping — user can verify later from account screen
    if (pendingUser) onAuth(pendingUser)
  }

  // ── Styles ─────────────────────────────────────────────────────────────────────
  const inputCls = 'w-full rounded-2xl px-4 py-3 text-base outline-none mb-3'
  const inputStyle = { background: '#141414', border: '0.5px solid #1e1e1e', color: '#e8e8e8' }

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-6" style={{ background: '#0a0a0a' }}>

      {/* Logo */}
      <div className="mb-10 text-center">
        <div className="font-black tracking-widest text-2xl mb-1" style={{ color: '#c9a84c', fontStyle: 'italic' }}>
          STABLEMONEY
        </div>
        <p className="text-xs" style={{ color: '#444' }}>Premium data bundles · NG &amp; GH</p>
      </div>

      {/* ── PIN GATE (returning user) ───────────────────────── */}
      {screen === 'pin_gate' && (
        <div className="w-full max-w-xs">
          <p className="text-center text-sm mb-6" style={{ color: '#888' }}>
            Welcome back,&nbsp;
            <span style={{ color: '#e8e8e8', fontWeight: 700 }}>{existingUserName?.split(' ')[0]}</span>
          </p>
          {loading
            ? <p className="text-center text-sm font-bold animate-pulse" style={{ color: '#c9a84c' }}>Verifying…</p>
            : <PinInput label="Enter your 4-digit PIN" onComplete={handlePinGate} error={error} />}
          <button
            onClick={async () => {
              await fetch('/api/auth/logout', { method: 'POST' })
              sessionStorage.removeItem('sm_user')
              go('choice')
            }}
            className="w-full text-xs py-3 mt-4 text-center"
            style={{ color: '#444' }}>
            Not you? Sign in to a different account
          </button>
        </div>
      )}

      {/* ── CHOICE ────────────────────────────────────────────── */}
      {screen === 'choice' && (
        <div className="w-full max-w-xs space-y-3">
          <button onClick={() => go('reg_phone')} className="btn-gold">Create Account</button>
          <button onClick={() => go('login_id')} className="btn-ghost">Sign In</button>
        </div>
      )}

      {/* ── REG: Phone ────────────────────────────────────────── */}
      {screen === 'reg_phone' && (
        <div className="w-full max-w-xs">
          <StepLabel>Step 1 of 5 — Phone number</StepLabel>
          <input type="tel" placeholder="08012345678" value={phone} autoFocus
            onChange={e => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
            className={inputCls} style={inputStyle} />
          <Err msg={error} />
          <button onClick={() => validatePhone() && go('reg_email')} className="btn-gold">Continue →</button>
          <Back onClick={() => go('choice')} />
        </div>
      )}

      {/* ── REG: Email ────────────────────────────────────────── */}
      {screen === 'reg_email' && (
        <div className="w-full max-w-xs">
          <StepLabel>Step 2 of 5 — Email address</StepLabel>
          <input type="email" placeholder="you@email.com" value={email} autoFocus
            onChange={e => setEmail(e.target.value)}
            className={inputCls} style={inputStyle} />
          <p className="text-[10px] mb-3" style={{ color: '#555' }}>
            We&apos;ll send a verification code to this email.
          </p>
          <Err msg={error} />
          <button onClick={() => validateEmail() && go('reg_name')} className="btn-gold">Continue →</button>
          <Back onClick={() => go('reg_phone')} />
        </div>
      )}

      {/* ── REG: Name ─────────────────────────────────────────── */}
      {screen === 'reg_name' && (
        <div className="w-full max-w-xs">
          <StepLabel>Step 3 of 5 — Full name</StepLabel>
          <input type="text" placeholder="Emeka Okafor" value={name} autoFocus
            onChange={e => setName(e.target.value)}
            className={inputCls} style={{ ...inputStyle, fontFamily: 'inherit' }} />
          <Err msg={error} />
          <button onClick={() => {
            if (name.trim().length < 2) { setError('Enter your full name'); return }
            setError(''); go('reg_password')
          }} className="btn-gold">Continue →</button>
          <Back onClick={() => go('reg_email')} />
        </div>
      )}

      {/* ── REG: Password ─────────────────────────────────────── */}
      {screen === 'reg_password' && (
        <div className="w-full max-w-xs">
          <StepLabel>Step 4 of 5 — Password</StepLabel>
          <div className="relative mb-3">
            <input
              type={showPassword ? 'text' : 'password'}
              placeholder="At least 8 characters"
              value={password} autoFocus
              onChange={e => setPassword(e.target.value)}
              className="w-full rounded-2xl px-4 py-3 text-base outline-none pr-12"
              style={inputStyle}
            />
            <button
              type="button"
              onClick={() => setShowPassword(s => !s)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-xs"
              style={{ color: '#555' }}>
              {showPassword ? 'HIDE' : 'SHOW'}
            </button>
          </div>
          {password.length > 0 && (
            <PasswordStrength password={password} />
          )}
          <Err msg={error} />
          <button onClick={() => {
            if (password.length < 8) { setError('Password must be at least 8 characters'); return }
            setError(''); go('reg_pin')
          }} className="btn-gold">Continue →</button>
          <Back onClick={() => go('reg_name')} />
        </div>
      )}

      {/* ── REG: PIN ──────────────────────────────────────────── */}
      {screen === 'reg_pin' && (
        <div className="w-full max-w-xs">
          <StepLabel>Step 5 of 5 — Create a 4-digit PIN</StepLabel>
          <p className="text-[10px] mb-4 text-center" style={{ color: '#555' }}>
            This PIN will be required every time you open the app.
          </p>
          {loading
            ? <p className="text-center text-sm font-bold animate-pulse" style={{ color: '#c9a84c' }}>Creating your account…</p>
            : <PinInput label="Create your 4-digit PIN" onComplete={handleRegisterPin} error={error} />}
          {!loading && <Back onClick={() => go('reg_password')} />}
        </div>
      )}

      {/* ── REG: Verify Email ─────────────────────────────────── */}
      {screen === 'reg_verify_email' && (
        <div className="w-full max-w-xs">
          <div className="text-center mb-6">
            <div className="text-3xl mb-3">📧</div>
            <p className="font-black text-sm" style={{ color: '#e8e8e8' }}>Check your email</p>
            <p className="text-xs mt-1" style={{ color: '#666' }}>
              We sent a 6-digit code to <span style={{ color: '#c9a84c' }}>{email || 'your email'}</span>
            </p>
          </div>
          <input
            type="text"
            placeholder="Enter 6-digit code"
            value={otp} autoFocus
            onChange={e => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
            className="w-full rounded-2xl px-4 py-3 text-xl text-center font-mono outline-none mb-3"
            style={{ ...inputStyle, letterSpacing: '0.3em' }}
          />
          <Err msg={error} />
          {loading
            ? <p className="text-center text-sm font-bold animate-pulse" style={{ color: '#c9a84c' }}>Verifying…</p>
            : (
              <>
                <button onClick={handleVerifyEmail} className="btn-gold">Verify Email →</button>
                <button onClick={handleResendOTP} className="w-full text-xs py-3 mt-2 text-center" style={{ color: '#444' }}>
                  Didn&apos;t get it? Resend code
                </button>
              </>
            )}
        </div>
      )}

      {/* ── LOGIN: Identifier ─────────────────────────────────── */}
      {screen === 'login_id' && (
        <div className="w-full max-w-xs">
          <StepLabel>Sign In</StepLabel>
          <input
            type="text"
            placeholder="Phone number or email"
            value={loginId} autoFocus
            onChange={e => setLoginId(e.target.value)}
            className={inputCls} style={inputStyle}
          />
          <div className="relative mb-3">
            <input
              type={showLoginPw ? 'text' : 'password'}
              placeholder="Password"
              value={loginPassword}
              onChange={e => setLoginPassword(e.target.value)}
              className="w-full rounded-2xl px-4 py-3 text-base outline-none pr-12"
              style={inputStyle}
            />
            <button
              type="button"
              onClick={() => setShowLoginPw(s => !s)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-xs"
              style={{ color: '#555' }}>
              {showLoginPw ? 'HIDE' : 'SHOW'}
            </button>
          </div>
          <Err msg={error} />
          {loading
            ? <p className="text-center text-sm font-bold animate-pulse" style={{ color: '#c9a84c' }}>Signing in…</p>
            : <button onClick={handleLogin} className="btn-gold">Sign In →</button>}
          <Back onClick={() => go('choice')} />
        </div>
      )}

      {/* ── ID VERIFICATION ──────────────────────────────────── */}
      {screen === 'id_verify' && (
        <div className="w-full max-w-xs">
          <div className="text-center mb-6">
            <div className="text-3xl mb-3">🪪</div>
            <p className="font-black text-sm" style={{ color: '#e8e8e8' }}>Verify your identity</p>
            <p className="text-xs mt-1" style={{ color: '#666' }}>
              Required for Nigerian users. Choose one method.
            </p>
          </div>

          {/* Toggle BVN / NIN */}
          <div className="flex rounded-full p-1 mb-4" style={{ background: '#141414', border: '0.5px solid #1e1e1e' }}>
            {(['BVN', 'NIN'] as const).map(type => (
              <button key={type}
                onClick={() => { setIdType(type); setIdNumber(''); setError('') }}
                className="flex-1 py-2 rounded-full text-xs font-black transition-all"
                style={idType === type
                  ? { background: '#1e1e1e', color: '#c9a84c', border: '0.5px solid #2e2a1e' }
                  : { color: '#444' }}>
                {type}
              </button>
            ))}
          </div>

          <p className="text-[10px] mb-2" style={{ color: '#555' }}>
            {idType === 'BVN'
              ? 'Bank Verification Number — 11 digits (dial *565*0# to retrieve yours)'
              : 'National Identification Number — 11 digits'}
          </p>
          <input
            type="tel"
            placeholder={`Enter your ${idType}`}
            value={idNumber} autoFocus
            onChange={e => setIdNumber(e.target.value.replace(/\D/g, '').slice(0, 11))}
            className="w-full rounded-2xl px-4 py-3 text-base font-mono text-center outline-none mb-3"
            style={{ ...inputStyle, letterSpacing: '0.15em' }}
          />
          <Err msg={error} />
          {loading
            ? <p className="text-center text-sm font-bold animate-pulse" style={{ color: '#c9a84c' }}>Verifying {idType}…</p>
            : (
              <>
                <button onClick={handleIdVerify} className="btn-gold">Verify {idType} →</button>
                <button onClick={skipIdVerify} className="w-full text-xs py-3 mt-2 text-center" style={{ color: '#444' }}>
                  Skip for now (some features may be limited)
                </button>
              </>
            )}

          {/* Security note */}
          <div className="mt-4 rounded-2xl p-3" style={{ background: '#0d0d0d', border: '0.5px solid #1e1e1e' }}>
            <p className="text-[9px] leading-relaxed" style={{ color: '#444' }}>
              🔒 Your {idType} is verified through a secure API and is never stored in full.
              We only store the last 4 digits after verification.
            </p>
          </div>
        </div>
      )}

    </div>
  )
}

// ── Sub-components ──────────────────────────────────────────────────────────────
function StepLabel({ children }: { children: React.ReactNode }) {
  return (
    <p className="text-[9px] font-black uppercase tracking-widest mb-2" style={{ color: '#555' }}>
      {children}
    </p>
  )
}

function Err({ msg }: { msg: string }) {
  if (!msg) return null
  return <p className="text-xs mb-3 text-center" style={{ color: '#c97070' }}>{msg}</p>
}

function Back({ onClick }: { onClick: () => void }) {
  return (
    <button onClick={onClick} className="w-full text-xs py-3 mt-2 text-center" style={{ color: '#444' }}>
      ← Back
    </button>
  )
}

function PasswordStrength({ password }: { password: string }) {
  const hasLength = password.length >= 8
  const hasUpper = /[A-Z]/.test(password)
  const hasNumber = /\d/.test(password)
  const hasSpecial = /[^A-Za-z0-9]/.test(password)
  const score = [hasLength, hasUpper, hasNumber, hasSpecial].filter(Boolean).length

  const bars = [
    { active: score >= 1, color: score <= 1 ? '#c97070' : score <= 2 ? '#c9a84c' : '#4caf7d' },
    { active: score >= 2, color: score <= 2 ? '#c9a84c' : '#4caf7d' },
    { active: score >= 3, color: '#4caf7d' },
    { active: score >= 4, color: '#4caf7d' },
  ]
  const label = score <= 1 ? 'Weak' : score === 2 ? 'Fair' : score === 3 ? 'Good' : 'Strong'
  const labelColor = score <= 1 ? '#c97070' : score === 2 ? '#c9a84c' : '#4caf7d'

  return (
    <div className="mb-3">
      <div className="flex gap-1.5 mb-1">
        {bars.map((b, i) => (
          <div key={i} className="h-1 flex-1 rounded-full transition-all"
            style={{ background: b.active ? b.color : '#1e1e1e' }} />
        ))}
      </div>
      <p className="text-[10px]" style={{ color: labelColor }}>{label} password</p>
    </div>
  )
}
