'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/lib/AuthContext'
import { ArrowUpRight, History } from 'lucide-react'
import { useRouter } from 'next/navigation'

export default function WalletPage() {
  const { token, user, loading: authLoading } = useAuth()
  const router = useRouter()
  const [amount, setAmount] = useState('')
  const [cashouts, setCashouts] = useState<any[]>([])
  const [loading, setLoading] = useState(false)

  useEffect(() => { if (!authLoading && !token) router.push('/login') }, [token, authLoading, router])
  useEffect(() => { if (!token) return; fetch('/api/wallet', { headers: { 'Authorization': `Bearer ${token}` } }).then(r => r.json()).then(d => setCashouts(d.requests || [])).catch(() => {}) }, [token])

  const handleCashout = async () => {
    if (!token || !amount) return
    setLoading(true)
    const res = await fetch('/api/wallet', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ amountFlh: parseInt(amount) }) })
    setLoading(false)
    const data = await res.json()
    if (res.ok) { setAmount(''); alert('Cashout submitted!') } else { alert(data.error) }
  }

  if (authLoading) return <div className="p-8 text-center text-gray-500">Loading...</div>
  if (!token) return null

  return (
    <div className="max-w-3xl mx-auto p-4 sm:p-6 space-y-6">
      <h1 className="text-2xl font-bold text-[#D4AF37]">Wallet</h1>
      <div className="bg-gradient-to-r from-[#D4AF37]/10 to-[#0a0a0f] border border-[#D4AF37]/20 rounded-lg p-6">
        <p className="text-sm text-gray-400 mb-1">Balance</p>
        <p className="text-4xl font-bold text-[#D4AF37]">{user?.flhBalance?.toLocaleString() || 0} <span className="text-lg text-gray-500">FLH</span></p>
      </div>
      <div className="bg-[#111118] border border-gray-800 rounded-lg p-6 space-y-4">
        <h2 className="font-semibold flex items-center gap-2"><ArrowUpRight size={16} className="text-[#D4AF37]" /> Cash Out</h2>
        <p className="text-xs text-gray-500">Rate: 100 FLH = £0.80 (20% platform spread). Minimum 100 FLH.</p>
        <div className="flex gap-2">
          <input type="number" placeholder="Amount (FLH)" value={amount} onChange={e => setAmount(e.target.value)} min={100}
            className="flex-1 bg-[#0a0a0f] border border-gray-700 rounded px-3 py-2 text-sm focus:border-[#D4AF37] outline-none" />
          <button onClick={handleCashout} disabled={loading || !amount || parseInt(amount) < 100}
            className="bg-[#D4AF37] text-[#0a0a0f] px-4 py-2 rounded text-sm font-semibold disabled:opacity-50 hover:bg-[#C9A84C] transition">
            {loading ? 'Processing...' : 'Cash Out'}
          </button>
        </div>
      </div>
      <div className="bg-[#111118] border border-gray-800 rounded-lg p-6 space-y-3">
        <h2 className="font-semibold flex items-center gap-2"><History size={16} className="text-[#D4AF37]" /> History</h2>
        {cashouts.length === 0 ? (
          <p className="text-sm text-gray-500">No cashout requests yet</p>
        ) : (
          cashouts.map(c => (
            <div key={c.id} className="flex items-center justify-between text-sm">
              <span className="text-gray-400">{c.amountFlh} FLH → £{c.fiatAmount.toFixed(2)}</span>
              <span className={`text-xs ${c.status === 'pending' ? 'text-yellow-400' : 'text-green-400'}`}>{c.status}</span>
            </div>
          ))
        )}
      </div>
    </div>
  )
}
