'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Navbar from '@/components/Navbar'
import { formatRupiah, formatDate } from '@/lib/utils'

export default function WalletPage() {
  const router = useRouter()
  const [balance, setBalance] = useState(0)
  const [transactions, setTransactions] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [topupAmount, setTopupAmount] = useState('')
  const [topupLoading, setTopupLoading] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    fetch('/api/wallet?limit=20')
      .then(r => r.json())
      .then(d => {
        setBalance(Number(d.balance || 0))
        setTransactions(d.transactions || [])
        setLoading(false)
      })
      .catch(() => setLoading(false))
  }, [])

  const handleTopup = async (e: React.FormEvent) => {
    e.preventDefault()
    const amount = Number(topupAmount)
    if (amount < 1000) {
      setError('Minimal topup Rp 1.000')
      return
    }

    setTopupLoading(true)
    setError('')
    try {
      const res = await fetch('/api/wallet', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount }),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Gagal membuat invoice')
      
      // We'll reuse the order checkout page UI for topup payments since it handles Cashify QRIS beautifully
      // To do this properly, we need to pass the invoice data to a payment page.
      // Since we generated Cashify directly, let's store it and redirect to a generic payment page
      sessionStorage.setItem(`topup_${data.transactionId}`, JSON.stringify({
        id: data.transactionId,
        productName: `Topup Saldo`,
        price: amount,
        totalAmount: data.totalAmount,
        uniqueCode: data.uniqueCode,
        status: 'pending',
        invoiceId: data.invoiceId,
        qrString: data.qrString,
        qrImageUrl: data.qrImageUrl,
        expiresAt: data.expiresAt,
      }))
      
      router.push(`/dashboard/wallet/pay/${data.transactionId}`)
    } catch (err: any) {
      setError(err.message)
      setTopupLoading(false)
    }
  }

  const predefinedAmounts = [10000, 20000, 50000, 100000, 200000, 500000]

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ paddingTop: '80px', maxWidth: '1000px', margin: '0 auto', padding: '80px 24px 60px', width: '100%' }}>
        <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '24px' }}>
          💰 Dompet & Saldo
        </h1>

        <div className="grid grid-cols-1 md:grid-cols-[1fr_1.5fr] gap-6 items-start">
          
          {/* Topup Card */}
          <div className="card" style={{ padding: '24px' }}>
            <div style={{ marginBottom: '24px', paddingBottom: '24px', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
              <div style={{ fontSize: '14px', color: '#64748b', marginBottom: '8px' }}>Total Saldo</div>
              <div style={{ fontSize: '36px', fontWeight: 700, color: '#f59e0b' }}>
                {loading ? <div className="skeleton" style={{ width: 150, height: 40, borderRadius: 8 }} /> : formatRupiah(balance)}
              </div>
            </div>

            <h3 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9', marginBottom: '16px' }}>Topup Saldo</h3>
            
            <form onSubmit={handleTopup}>
              {error && (
                <div style={{ padding: '10px', background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: '8px', color: '#ef4444', fontSize: '13px', marginBottom: '16px' }}>
                  ❌ {error}
                </div>
              )}

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px', marginBottom: '16px' }}>
                {predefinedAmounts.map(amt => (
                  <button
                    key={amt}
                    type="button"
                    onClick={() => setTopupAmount(amt.toString())}
                    style={{
                      padding: '8px',
                      background: topupAmount === amt.toString() ? 'rgba(245,158,11,0.15)' : 'rgba(255,255,255,0.03)',
                      border: `1px solid ${topupAmount === amt.toString() ? 'rgba(245,158,11,0.5)' : 'rgba(255,255,255,0.08)'}`,
                      borderRadius: '8px',
                      color: topupAmount === amt.toString() ? '#f59e0b' : '#94a3b8',
                      fontSize: '13px',
                      cursor: 'pointer',
                    }}
                  >
                    {formatRupiah(amt)}
                  </button>
                ))}
              </div>

              <div style={{ marginBottom: '20px' }}>
                <label className="label">Nominal Lain (Rp)</label>
                <input
                  className="input"
                  type="number"
                  placeholder="Min. 1000"
                  value={topupAmount}
                  onChange={e => setTopupAmount(e.target.value)}
                  min="1000"
                />
              </div>

              <button
                type="submit"
                className="btn btn-primary"
                style={{ width: '100%', padding: '12px' }}
                disabled={!topupAmount || Number(topupAmount) < 10000 || topupLoading}
              >
                {topupLoading ? <span className="spinner" /> : 'Lanjut Pembayaran'}
              </button>
            </form>
          </div>

          {/* History Card */}
          <div className="card" style={{ overflow: 'hidden' }}>
            <div style={{ padding: '20px 24px', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
              <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#f1f5f9' }}>Riwayat Transaksi</h2>
            </div>

            {loading ? (
              <div style={{ padding: '24px' }}>
                {Array(4).fill(0).map((_, i) => <div key={i} className="skeleton" style={{ height: 60, borderRadius: 10, marginBottom: 12 }} />)}
              </div>
            ) : transactions.length === 0 ? (
              <div style={{ padding: '60px 24px', textAlign: 'center', color: '#475569' }}>
                <div style={{ fontSize: '40px', marginBottom: '12px' }}>📝</div>
                <p>Belum ada riwayat transaksi</p>
              </div>
            ) : (
              <div style={{ padding: '8px' }}>
                {transactions.map(tx => {
                  const isPositive = tx.type === 'TOPUP' || tx.type === 'REFUND' || tx.type === 'BONUS'
                  return (
                    <div key={tx.id} style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      padding: '14px 16px',
                      borderRadius: '10px',
                      transition: 'background 0.2s',
                    }}
                      onMouseEnter={e => (e.currentTarget as HTMLElement).style.background = 'rgba(255,255,255,0.03)'}
                      onMouseLeave={e => (e.currentTarget as HTMLElement).style.background = 'transparent'}
                    >
                      <div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                          <span style={{
                            padding: '2px 6px', borderRadius: '4px', fontSize: '10px', fontWeight: 700,
                            background: isPositive ? 'rgba(16,185,129,0.1)' : 'rgba(239,68,68,0.1)',
                            color: isPositive ? '#10b981' : '#ef4444',
                          }}>
                            {tx.type}
                          </span>
                          <span style={{ fontSize: '14px', fontWeight: 500, color: '#e2e8f0' }}>{tx.description}</span>
                        </div>
                        <div style={{ fontSize: '12px', color: '#64748b' }}>
                          {formatDate(tx.createdAt)} • Status: 
                          <span style={{ 
                            marginLeft: 4, 
                            color: tx.status === 'SUCCESS' ? '#10b981' : tx.status === 'PENDING' ? '#f59e0b' : '#ef4444' 
                          }}>
                            {tx.status}
                          </span>
                        </div>
                      </div>
                      <div style={{ fontSize: '16px', fontWeight: 700, color: isPositive ? '#10b981' : '#ef4444', textAlign: 'right' }}>
                        {isPositive ? '+' : '-'}{formatRupiah(tx.amount)}
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </main>
  )
}
