'use client'
import { useState } from 'react'
import DataCard from './DataCard'
import { NG_BUNDLES, Bundle } from '@/lib/data'

interface UserData {
  id: string; name: string; phone: string; email: string; walletNGN: number
  emailVerified?: boolean; idVerified?: boolean; idType?: string
  virtualAccountNumber?: string; virtualAccountBank?: string; virtualAccountName?: string
}
interface Props {
  user: UserData
  onBalanceUpdate: (n: number) => void
  onLogout: () => void
}

const grouped = NG_BUNDLES.reduce<Record<string, Bundle[]>>((acc, b) => {
  acc[b.network] = acc[b.network] ?? []
  acc[b.network].push(b)
  return acc
}, {})

export default function NigeriaStore({ user, onBalanceUpdate }: Props) {
  const [selected, setSelected]    = useState<Bundle | null>(null)
  const [phone, setPhone]          = useState('')
  const [loading, setLoading]      = useState(false)
  const [error, setError]          = useState('')
  const [toast, setToast]          = useState('')
  const [copied, setCopied]        = useState(false)
  const [creatingDVA, setCreating] = useState(false)
  const [dva, setDva]              = useState({
    number: user.virtualAccountNumber,
    bank:   user.virtualAccountBank,
    name:   user.virtualAccountName,
  })

  function showToast(msg: string) {
    setToast(msg); setTimeout(() => setToast(''), 3500)
  }

  function copyAccount() {
    if (!dva.number) return
    navigator.clipboard.writeText(dva.number).then(() => {
      setCopied(true); setTimeout(() => setCopied(false), 2000)
    })
  }

  async function createDVA() {
    setCreating(true)
    try {
      const res  = await fetch('/api/user/virtual-account', { method: 'POST' })
      const data = await res.json()
      if (!res.ok) { showToast(data.error ?? 'Could not create account'); return }
      setDva({ number: data.virtualAccountNumber, bank: data.virtualAccountBank, name: data.virtualAccountName })
      showToast('Virtual account created!')
    } catch { showToast('Network error — try again') }
    finally { setCreating(false) }
  }

  async function handleBuy() {
    setError('')
    if (!/^0[789]\d{9}$/.test(phone)) {
      setError('Enter a valid Nigerian number (e.g. 08012345678)')
      return
    }
    if (!selected) return
    if (user.walletNGN < selected.price) {
      setError('Insufficient balance. Fund your wallet to continue.')
      return
    }
    setLoading(true)
    try {
      const res  = await fetch('/api/wallet/buy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ bundleId: selected.id, recipientPhone: phone }),
      })
      const data = await res.json()
      if (!res.ok) { setError(data.error); setLoading(false); return }
      onBalanceUpdate(data.newBalance)
      setSelected(null); setPhone('')
      showToast(data.message)
    } catch { setError('Network error — please try again') }
    finally { setLoading(false) }
  }

  const fmt = (n: number) => '₦' + n.toLocaleString('en-NG', { minimumFractionDigits: 2 })

  return (
    // position:relative keeps the modal overlay contained
    <div className="relative">
      <div className="p-4 max-w-lg mx-auto pb-28">

        {/* Wallet card */}
        <div className="rounded-3xl p-5 mb-5" style={{ background: '#111', border: '0.5px solid #1e1e1e' }}>
          <div className="flex justify-between items-start mb-1">
            <span className="text-[9px] font-black uppercase tracking-widest" style={{ color: '#555' }}>NGN Wallet</span>
            <span className="text-[9px] font-bold" style={{ color: '#555' }}>👤 {user.name.split(' ')[0]}</span>
          </div>
          <div className="text-4xl font-black mt-1 mb-4" style={{ color: '#c9a84c', letterSpacing: '-1px' }}>
            {fmt(user.walletNGN)}
          </div>

          <div style={{ borderTop: '0.5px solid #1e1e1e', paddingTop: '14px' }}>
            {dva.number ? (
              <>
                <p className="text-[9px] uppercase tracking-widest mb-0.5" style={{ color: '#444' }}>Fund via Bank Transfer</p>
                <p className="text-[9px] mb-2" style={{ color: '#555' }}>{dva.bank} · {dva.name}</p>
                <div className="flex justify-between items-center">
                  <span className="font-mono font-black text-xl" style={{ color: '#e8d5a0', letterSpacing: '0.04em' }}>{dva.number}</span>
                  <button
                    onClick={copyAccount}
                    className="text-[9px] font-black px-3 py-2 rounded-xl transition-all active:scale-95"
                    style={{ background: '#1e1e1e', color: '#c9a84c', border: '0.5px solid #2e2a1e' }}
                  >
                    {copied ? '✓ COPIED' : 'COPY'}
                  </button>
                </div>
                <p className="text-[9px] mt-2" style={{ color: '#333' }}>Transfer any amount — wallet credited instantly</p>
              </>
            ) : (
              <>
                <p className="text-[9px] mb-3" style={{ color: '#555' }}>No virtual account yet</p>
                <button
                  onClick={createDVA}
                  disabled={creatingDVA}
                  className="text-xs font-black px-4 py-2 rounded-xl transition-all active:scale-95 disabled:opacity-50"
                  style={{ background: '#1e1e1e', color: '#c9a84c', border: '0.5px solid #2e2a1e' }}
                >
                  {creatingDVA ? 'Creating…' : 'Get Account Number'}
                </button>
              </>
            )}
          </div>
        </div>

        {/* Bundles */}
        {Object.entries(grouped).map(([network, bundles]) => (
          <div key={network} className="mb-4">
            <p className="section-label">{network}</p>
            {bundles.map((bundle) => (
              <DataCard
                key={bundle.id}
                bundle={bundle}
                symbol="₦"
                onClick={() => { setSelected(bundle); setError(''); setPhone('') }}
                loading={loading && selected?.id === bundle.id}
              />
            ))}
          </div>
        ))}
      </div>

      {/* Toast */}
      {toast && (
        <div className="absolute left-3 right-3 z-50 text-xs font-bold px-5 py-3 rounded-2xl text-center"
          style={{ top: '12px', background: '#c9a84c', color: '#0a0a0a' }}>
          {toast}
        </div>
      )}

      {/* Buy modal — absolute positioned (NOT fixed) for WebViewGold */}
      {selected && (
        <div
          className="absolute inset-0 z-50 flex items-end"
          style={{ background: 'rgba(0,0,0,0.75)' }}
          onClick={() => setSelected(null)}
        >
          <div
            className="w-full rounded-t-3xl p-6 pb-10"
            style={{ background: '#0f0f0f', borderTop: '0.5px solid #2a2a2a' }}
            onClick={e => e.stopPropagation()}
          >
            <div className="w-10 h-1 rounded-full mx-auto mb-5" style={{ background: '#2a2a2a' }} />

            <h2 className="font-black text-lg mb-1" style={{ color: '#e8d5a0' }}>{selected.name}</h2>
            <p className="text-[11px] mb-4" style={{ color: '#555' }}>
              {(selected.dataMB >= 1024 ? `${selected.dataMB / 1024}GB` : `${selected.dataMB}MB`)} · {selected.validityDays} days
            </p>

            {/* Balance row */}
            <div className="flex justify-between items-center rounded-xl px-4 py-3 mb-4"
              style={{ background: '#141414', border: '0.5px solid #1e1e1e' }}>
              <span className="text-xs" style={{ color: '#555' }}>Wallet balance</span>
              <span className="font-black text-sm" style={{ color: user.walletNGN < selected.price ? '#c97070' : '#c9a84c' }}>
                {fmt(user.walletNGN)}
              </span>
            </div>

            {user.walletNGN < selected.price ? (
              <div className="rounded-xl px-4 py-3 text-xs font-medium mb-4"
                style={{ background: '#1a1000', border: '0.5px solid #3a2a00', color: '#c9a84c' }}>
                ⚠ You need {fmt(selected.price - user.walletNGN)} more. Transfer to your account above to top up.
              </div>
            ) : (
              <>
                <label className="text-[9px] font-black uppercase tracking-widest block mb-1.5" style={{ color: '#555' }}>
                  Recipient Phone Number
                </label>
                <input
                  type="tel"
                  placeholder="08012345678"
                  value={phone}
                  onChange={e => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
                  className="input-dark font-mono mb-4"
                />
              </>
            )}

            {error && (
              <p className="text-xs mb-3 px-3 py-2 rounded-xl" style={{ color: '#c97070', background: '#1e0000', border: '0.5px solid #3e1e1e' }}>
                {error}
              </p>
            )}

            {user.walletNGN >= selected.price && (
              <button onClick={handleBuy} disabled={loading} className="btn-gold">
                {loading ? 'Processing…' : `Pay ₦${selected.price.toLocaleString()} from Wallet`}
              </button>
            )}

            <p className="text-[9px] text-center mt-3" style={{ color: '#2a2a2a' }}>
              Instant delivery · No extra charges
            </p>
          </div>
        </div>
      )}
    </div>
  )
}
