import { useState, useEffect } from 'react'
import { useForm, router, usePage } from '@inertiajs/react'

export default function ProfileScreen() {
  const { auth, flash } = usePage().props
  const user = auth?.user ?? {}
  const [openSection, setOpenSection] = useState(null)
  const [transactions, setTransactions] = useState([])
  const [txLoading, setTxLoading] = useState(false)

  // Password form
  const pwForm = useForm({ current_password: '', password: '', password_confirmation: '' })

  // Coupon form
  const couponForm = useForm({ code: '' })

  const toggleSection = (id) => setOpenSection(openSection === id ? null : id)

  // Load transactions when section opens
  useEffect(() => {
    if (openSection !== 'transactions') return
    if (transactions.length > 0) return
    setTxLoading(true)
    fetch('/profile/transactions', {
      headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
      credentials: 'same-origin',
    })
      .then(r => r.json())
      .then(d => setTransactions(d.data ?? []))
      .catch(() => {})
      .finally(() => setTxLoading(false))
  }, [openSection])

  const handleLogout = () => {
    router.post('/logout')
  }

  const inputStyle = {
    width: '100%', background: '#0A0E1A', border: '1px solid rgba(255,255,255,0.1)',
    borderRadius: '8px', padding: '10px 12px', color: '#F0F4FF', fontSize: '14px',
    outline: 'none', marginBottom: '8px', boxSizing: 'border-box',
  }

  const btnGreen = {
    background: '#00E676', color: '#000', fontWeight: '700', fontSize: '13px',
    padding: '10px 20px', borderRadius: '8px', border: 'none', cursor: 'pointer',
  }

  return (
    <div style={{ paddingBottom: '100px' }}>
      {/* Flash messages */}
      {flash?.success && (
        <div style={{ margin:'12px 16px', padding:'12px 16px', background:'rgba(0,230,118,0.1)', border:'1px solid rgba(0,230,118,0.3)', borderRadius:'10px', color:'#00E676', fontSize:'14px' }}>
          ✓ {flash.success}
        </div>
      )}

      {/* User header */}
      <div style={{ padding:'24px 20px', textAlign:'center' }}>
        <div style={{ width:'64px', height:'64px', borderRadius:'50%', background:'rgba(0,230,118,0.15)', border:'2px solid #00E676', display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto 12px', fontSize:'24px', fontWeight:'700', color:'#00E676' }}>
          {(user.name || 'U').charAt(0).toUpperCase()}
        </div>
        <div style={{ fontWeight:'700', fontSize:'18px', color:'#F0F4FF' }}>{user.name}</div>
        <div style={{ color:'#6B7A9F', fontSize:'13px', marginTop:'4px' }}>{user.email}</div>
      </div>

      {/* Stats */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'8px', margin:'0 16px 16px' }}>
        {[
          { label:'Demo', value:'$'+Number(user.demo_balance||0).toFixed(2), color:'#60A5FA' },
          { label:'Real', value:'$'+Number(user.real_balance||0).toFixed(2), color:'#00E676' },
          { label:'Bonus', value:'$'+Number(user.bonus_balance||0).toFixed(2), color:'#FFD700' },
        ].map(s => (
          <div key={s.label} style={{ background:'#1C2333', borderRadius:'10px', padding:'12px', textAlign:'center' }}>
            <div style={{ color:s.color, fontWeight:'700', fontSize:'16px' }}>{s.value}</div>
            <div style={{ color:'#6B7A9F', fontSize:'11px', marginTop:'2px' }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* Deposit button */}
      <div style={{ margin:'0 16px 16px' }}>
        <button onClick={() => router.visit('/deposit')} style={{ ...btnGreen, width:'100%', padding:'14px' }}>
          + Deposit Funds
        </button>
      </div>

      {/* Coupon */}
      <div style={{ margin:'0 16px 16px', padding:'16px', background:'#1C2333', borderRadius:'12px', border:'1px solid rgba(255,255,255,0.06)' }}>
        <div style={{ fontSize:'13px', fontWeight:'600', color:'#F0F4FF', marginBottom:'10px' }}>🎁 Redeem Coupon</div>
        {couponForm.errors?.coupon && (
          <div style={{ color:'#FF3D57', fontSize:'12px', marginBottom:'8px' }}>✗ {couponForm.errors.coupon}</div>
        )}
        <div style={{ display:'flex', gap:'8px' }}>
          <input
            type="text"
            value={couponForm.data.code}
            onChange={e => couponForm.setData('code', e.target.value.toUpperCase())}
            placeholder="Enter coupon code"
            style={{ ...inputStyle, marginBottom:0, fontFamily:'monospace', letterSpacing:'0.08em' }}
          />
          <button
            onClick={() => couponForm.post('/profile/coupon', { preserveScroll: true, onSuccess: () => couponForm.reset() })}
            disabled={couponForm.processing || !couponForm.data.code.trim()}
            style={{ ...btnGreen, opacity: (couponForm.processing || !couponForm.data.code.trim()) ? 0.5 : 1, whiteSpace:'nowrap' }}
          >
            {couponForm.processing ? '...' : 'Apply'}
          </button>
        </div>
      </div>

      {/* ACCOUNT section */}
      <div style={{ margin:'0 16px', color:'#6B7A9F', fontSize:'12px', fontWeight:'600', letterSpacing:'0.08em', marginBottom:'8px' }}>ACCOUNT</div>
      <div style={{ margin:'0 16px 16px', background:'#1C2333', borderRadius:'12px', border:'1px solid rgba(255,255,255,0.06)', overflow:'hidden' }}>

        {/* Verification */}
        <div>
          <div onClick={() => toggleSection('kyc')} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'16px 20px', cursor:'pointer', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
            <span style={{ color:'#F0F4FF' }}>Verification</span>
            <div style={{ display:'flex', alignItems:'center', gap:'8px' }}>
              <span style={{ fontSize:'11px', background:'rgba(255,215,0,0.1)', color:'#FFD700', padding:'2px 8px', borderRadius:'20px' }}>Unverified</span>
              <span style={{ color:'#6B7A9F' }}>›</span>
            </div>
          </div>
          {openSection === 'kyc' && (
            <div style={{ padding:'16px 20px', background:'rgba(255,255,255,0.02)', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
              <p style={{ color:'#6B7A9F', fontSize:'13px', marginBottom:'12px' }}>Submit your ID documents to verify your account and unlock full withdrawal access.</p>
              <div style={{ color:'#6B7A9F', fontSize:'13px' }}>📧 Send documents to: <a href="mailto:kyc@optiqo.com" style={{ color:'#00E676' }}>kyc@optiqo.com</a></div>
            </div>
          )}
        </div>

        {/* Transaction History */}
        <div>
          <div onClick={() => toggleSection('transactions')} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'16px 20px', cursor:'pointer', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
            <span style={{ color:'#F0F4FF' }}>Transaction History</span>
            <span style={{ color:'#6B7A9F' }}>›</span>
          </div>
          {openSection === 'transactions' && (
            <div style={{ padding:'16px 20px', background:'rgba(255,255,255,0.02)', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
              {txLoading ? (
                <div style={{ color:'#6B7A9F', textAlign:'center', padding:'20px' }}>Loading...</div>
              ) : transactions.length === 0 ? (
                <div style={{ color:'#6B7A9F', textAlign:'center', padding:'20px' }}>No transactions yet.</div>
              ) : transactions.map((tx, i) => (
                <div key={i} style={{ display:'flex', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
                  <div>
                    <div style={{ color:'#F0F4FF', fontSize:'14px' }}>{tx.type}</div>
                    <div style={{ color:'#6B7A9F', fontSize:'12px' }}>{tx.date} · <span style={{ color: tx.status === 'approved' ? '#00E676' : tx.status === 'rejected' ? '#FF3D57' : '#FFD700' }}>{tx.status}</span></div>
                  </div>
                  <div style={{ color: tx.amount >= 0 ? '#00E676' : '#FF3D57', fontWeight:'600' }}>
                    {tx.amount >= 0 ? '+' : ''}${Math.abs(tx.amount).toFixed(2)}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Settings / Change Password */}
        <div>
          <div onClick={() => toggleSection('settings')} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'16px 20px', cursor:'pointer', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
            <span style={{ color:'#F0F4FF' }}>Settings</span>
            <span style={{ color:'#6B7A9F' }}>›</span>
          </div>
          {openSection === 'settings' && (
            <div style={{ padding:'16px 20px', background:'rgba(255,255,255,0.02)', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
              <div style={{ fontWeight:'600', color:'#F0F4FF', marginBottom:'12px', fontSize:'14px' }}>Change Password</div>
              {pwForm.errors?.current_password && <div style={{ color:'#FF3D57', fontSize:'12px', marginBottom:'8px' }}>✗ {pwForm.errors.current_password}</div>}
              {pwForm.recentlySuccessful && <div style={{ color:'#00E676', fontSize:'12px', marginBottom:'8px' }}>✓ Password changed successfully.</div>}
              <input type="password" placeholder="Current password" value={pwForm.data.current_password} onChange={e => pwForm.setData('current_password', e.target.value)} style={inputStyle} />
              <input type="password" placeholder="New password" value={pwForm.data.password} onChange={e => pwForm.setData('password', e.target.value)} style={inputStyle} />
              <input type="password" placeholder="Confirm new password" value={pwForm.data.password_confirmation} onChange={e => pwForm.setData('password_confirmation', e.target.value)} style={inputStyle} />
              <button onClick={() => pwForm.put('/profile/password', { preserveScroll: true, onSuccess: () => pwForm.reset() })} disabled={pwForm.processing} style={{ ...btnGreen, opacity: pwForm.processing ? 0.6 : 1 }}>
                {pwForm.processing ? 'Saving...' : 'Change Password'}
              </button>
            </div>
          )}
        </div>

        {/* Support */}
        <div>
          <div onClick={() => toggleSection('support')} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'16px 20px', cursor:'pointer', borderBottom:'1px solid rgba(255,255,255,0.04)' }}>
            <span style={{ color:'#F0F4FF' }}>Support</span>
            <span style={{ color:'#6B7A9F' }}>›</span>
          </div>
          {openSection === 'support' && (
            <div style={{ padding:'16px 20px', background:'rgba(255,255,255,0.02)', borderBottom:'1px solid rgba(255,255,255,0.04)', display:'flex', flexDirection:'column', gap:'10px' }}>
              <a href="https://wa.me/+8801700000000" target="_blank" style={{ display:'flex', alignItems:'center', gap:'10px', padding:'12px 16px', background:'rgba(0,230,118,0.08)', border:'1px solid rgba(0,230,118,0.2)', borderRadius:'10px', color:'#00E676', textDecoration:'none', fontSize:'14px' }}>
                💬 WhatsApp Support
              </a>
              <a href="mailto:support@optiqo.com" style={{ display:'flex', alignItems:'center', gap:'10px', padding:'12px 16px', background:'rgba(255,255,255,0.04)', border:'1px solid rgba(255,255,255,0.08)', borderRadius:'10px', color:'#F0F4FF', textDecoration:'none', fontSize:'14px' }}>
                📧 Email Support
              </a>
              <a href="https://t.me/optiqo" target="_blank" style={{ display:'flex', alignItems:'center', gap:'10px', padding:'12px 16px', background:'rgba(0,136,204,0.08)', border:'1px solid rgba(0,136,204,0.2)', borderRadius:'10px', color:'#0088cc', textDecoration:'none', fontSize:'14px' }}>
                ✈️ Telegram
              </a>
            </div>
          )}
        </div>

        {/* Log Out */}
        <div onClick={handleLogout} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'16px 20px', cursor:'pointer' }}>
          <span style={{ color:'#FF3D57' }}>Log Out</span>
          <span style={{ color:'#FF3D57' }}>›</span>
        </div>

      </div>
    </div>
  )
}
