'use client'
import { useState, useRef } from 'react'
import { Bundle, formatMB } from '@/lib/data'

interface Props {
  bundle: Bundle
  country: 'GH' | 'NG'
  symbol: string
  onClose: () => void
}

export default function PhoneModal({ bundle, country, symbol, onClose }: Props) {
  const [phone, setPhone]     = useState('')
  const [email, setEmail]     = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError]     = useState('')

  // ── WebViewGold redirect fix ───────────────────────────────────────────────
  // window.location.href is unreliable inside WebViewGold WebView.
  // The reliable fix: create a hidden <a> tag and programmatically click it.
  // WebViewGold intercepts anchor clicks correctly for external navigation.
  const linkRef = useRef<HTMLAnchorElement>(null)

  function navigateToPaystack(url: string) {
    if (linkRef.current) {
      linkRef.current.href = url
      linkRef.current.click()
    } else {
      // Fallback chain — try every method
      try { window.location.replace(url) } catch {
        try { window.location.assign(url) } catch {
          window.location.href = url
        }
      }
    }
  }

  async function handlePay() {
    setError('')

    if (!phone || phone.replace(/\D/g, '').length < 10) {
      setError('Enter a valid phone number (at least 10 digits)')
      return
    }
    if (!email || !email.includes('@')) {
      setError('Enter a valid email address')
      return
    }

    setLoading(true)
    try {
      const res = await fetch('/api/paystack', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          amount: bundle.price,
          email,
          currency: country === 'GH' ? 'GHS' : 'NGN',
          bundleId: bundle.id,
          recipientPhone: phone,
          country,
        }),
      })

      const data = await res.json()

      if (!res.ok || !data.url) {
        setError(data.error ?? 'Could not initiate payment. Try again.')
        setLoading(false)
        return
      }

      // ── Navigate to Paystack using anchor click (WebView safe) ───────────
      navigateToPaystack(data.url)

      // Don't setLoading(false) — we're navigating away.
      // If navigation fails for some reason, timeout and reset.
      setTimeout(() => setLoading(false), 5000)

    } catch {
      setError('Network error. Please check your connection.')
      setLoading(false)
    }
  }

  const networkColors: Record<string, string> = {
    MTN:     'bg-[#1e1a00] text-[#c9a84c] border border-[#2e2a1e]',
    Airtel:  'bg-[#1e0000] text-[#c97070] border border-[#2e1e1e]',
    Glo:     'bg-[#001e08] text-[#70c9a0] border border-[#1e2e20]',
    '9mobile':'bg-[#001a12] text-[#70c9b0] border border-[#1e2e28]',
    AT:      'bg-[#00101e] text-[#70a0c9] border border-[#1e202e]',
    Telecel: 'bg-[#1e0000] text-[#c97070] border border-[#2e1e1e]',
  }
  const netColor = networkColors[bundle.network] ?? 'bg-[#1a1a1a] text-[#888]'

  return (
    <>
      {/* ── Hidden anchor for WebViewGold-safe navigation ────────────────── */}
      {/* eslint-disable-next-line jsx-a11y/anchor-has-content */}
      <a ref={linkRef} href="#" style={{ display: 'none' }} aria-hidden="true" />

      {/* ── Modal backdrop ───────────────────────────────────────────────── */}
      {/*
        IMPORTANT: do NOT use position:fixed here — it collapses inside WebViewGold.
        Use a full-height flex container inside the normal flow instead.
        The parent page.tsx wraps everything in a min-h-screen div.
      */}
      <div
        className="absolute inset-0 z-50 flex items-end"
        style={{ background: 'rgba(0,0,0,0.7)' }}
        onClick={onClose}
      >
        <div
          className="w-full rounded-t-3xl p-6 pb-10"
          style={{ background: '#0f0f0f', borderTop: '0.5px solid #2a2a2a' }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Handle */}
          <div className="w-10 h-1 rounded-full mx-auto mb-5" style={{ background: '#2a2a2a' }} />

          {/* Bundle header */}
          <div className="flex items-center gap-3 mb-4">
            <div className={`net-badge ${netColor}`}>
              {bundle.network.substring(0, 2)}
            </div>
            <div>
              <h2 className="font-black text-lg" style={{ color: '#e8d5a0' }}>{bundle.name}</h2>
              <p className="text-[11px]" style={{ color: '#555' }}>
                {formatMB(bundle.dataMB)} · {bundle.validityDays} days · {symbol}{bundle.price.toLocaleString()}
              </p>
            </div>
          </div>

          {/* Recipient phone */}
          <label className="text-[9px] font-black uppercase tracking-widest block mb-1.5" style={{ color: '#555' }}>
            Recipient Phone Number
          </label>
          <input
            type="tel"
            placeholder={country === 'GH' ? '024XXXXXXX' : '0812XXXXXXX'}
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            className="input-dark font-mono mb-3"
          />

          {/* Email */}
          <label className="text-[9px] font-black uppercase tracking-widest block mb-1.5" style={{ color: '#555' }}>
            Your Email (for receipt)
          </label>
          <input
            type="email"
            placeholder="you@example.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="input-dark 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>
          )}

          <button onClick={handlePay} disabled={loading} className="btn-gold">
            {loading
              ? 'Redirecting to Paystack…'
              : `Pay ${symbol}${bundle.price.toLocaleString()} via ${country === 'GH' ? 'MoMo / Card' : 'Card'}`}
          </button>

          <p className="text-[9px] text-center mt-3" style={{ color: '#333' }}>
            Secured by Paystack · {country === 'GH' ? 'MoMo prompt sent to your phone' : 'Card or bank transfer'}
          </p>
        </div>
      </div>
    </>
  )
}
