import { useState, useEffect } from 'react'
import { Shell } from '@/layouts/Shell'
import { financialService, LedgerEntry } from '@/services/financialService'
import { FaMoneyCheck } from 'react-icons/fa6'

export function WalletPage() {
    const [balance, setBalance] = useState<number>(0)
    const [ledger, setLedger] = useState<LedgerEntry[]>([])
    const [loading, setLoading] = useState(true)
    const [requesting, setRequesting] = useState(false)

    useEffect(() => {
        loadFinancials()
    }, [])

    const loadFinancials = async () => {
        setLoading(true)
        try {
            const b = await financialService.getBalance()
            setBalance(b)
            const l = await financialService.getLedger()
            setLedger(l.entries || [])
        } catch (err) {
            console.error('Failed to load financials', err)
        } finally {
            setLoading(false)
        }
    }

    const handleWithdrawal = async () => {
        if (balance <= 0) {
            alert('Saldo insuficiente para saque.')
            return
        }
        const amountStr = prompt('Digite o valor para saque (ex: 100.00):')
        if (!amountStr) return
        const amount = parseFloat(amountStr)
        if (isNaN(amount) || amount <= 0) {
            alert('Valor inválido')
            return
        }

        // Convert to cents? Backend expects integer or float?
        // Go backend usually expects cents (int64) or handles float if JSON field matches.
        // UseCase says Amount is int64 (cents).
        // Controller `RequestWithdrawal` reads JSON into `WithdrawalRequest`. 
        // `type WithdrawalRequest struct { Amount int64 ... }`.
        // So we must send CENTS.
        // Wait, the handler decodes JSON: `var req struct { Amount int64 ... }`.
        // So yes, cents.

        // BUT `financialService.ts` currently typed as `number`.
        // Let's assume input is in currency (R$) and we convert to cents.
        const cents = Math.floor(amount * 100)

        setRequesting(true)
        try {
            await financialService.requestWithdrawal(cents)
            alert('Solicitação de saque realizada com sucesso!')
            loadFinancials()
        } catch (err) {
            console.error(err)
            alert('Erro ao solicitar saque.')
        } finally {
            setRequesting(false)
        }
    }

    const formatCurrency = (cents: number | null | undefined) => {
        const safe = typeof cents === 'number' && !isNaN(cents) ? cents : 0
        return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(safe / 100)
    }

    return (
        <Shell>
            <div className="space-y-6 max-w-5xl mx-auto">
                <div className="flex justify-between items-center">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-800">Minha Carteira</h1>
                        <p className="text-gray-600">Gestão financeira e extrato.</p>
                    </div>
                    <button
                        onClick={handleWithdrawal}
                        disabled={requesting || balance <= 0}
                        className="px-6 py-2 rounded-lg font-medium shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 text-white hover:opacity-90 transition"
                        style={{ backgroundColor: '#0F4C81' }}
                    >
                        <FaMoneyCheck size={18} color="white" />
                        {requesting ? 'Processando...' : 'Solicitar Saque'}
                    </button>
                </div>

                {/* Balance Card */}
                <div className="rounded-xl shadow-lg p-8 text-white" style={{ backgroundColor: '#0F4C81' }}>
                    <p className="text-blue-100 uppercase text-xs font-semibold tracking-wider mb-1">Saldo Disponível</p>
                    <div className="text-4xl font-bold">{formatCurrency(balance)}</div>
                    <p className="text-blue-200 text-sm mt-2">Valores de vendas confirmadas e entregues.</p>
                </div>

                {/* Ledger Table */}
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
                    <div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center">
                        <h3 className="font-semibold text-gray-800">Extrato de Transações</h3>
                        <button onClick={loadFinancials} className="text-sm hover:underline font-medium" style={{ color: '#0F4C81' }}>Atualizar</button>
                    </div>

                    {loading ? (
                        <div className="p-8 text-center text-gray-500">Carregando extrato...</div>
                    ) : ledger.length === 0 ? (
                        <div className="p-8 text-center text-gray-500">Nenhuma transação encontrada.</div>
                    ) : (
                        <table className="w-full text-left">
                            <thead className="text-white border-b border-gray-100" style={{ backgroundColor: '#0F4C81' }}>
                                <tr>
                                    <th className="px-6 py-3 text-xs font-medium text-white uppercase">Data</th>
                                    <th className="px-6 py-3 text-xs font-medium text-white uppercase">Descrição</th>
                                    <th className="px-6 py-3 text-xs font-medium text-white uppercase">Tipo</th>
                                    <th className="px-6 py-3 text-xs font-medium text-white uppercase text-right">Valor</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {ledger.map((entry) => (
                                    <tr key={entry.id} className="hover:bg-gray-50 transition-colors">
                                        <td className="px-6 py-3 text-sm text-gray-600">
                                            {new Date(entry.created_at).toLocaleDateString()} {new Date(entry.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                        </td>
                                        <td className="px-6 py-3 text-sm text-gray-800 font-medium">
                                            {entry.description}
                                            <span className="block text-xs text-gray-400 font-normal truncate max-w-[200px]">{entry.id}</span>
                                        </td>
                                        <td className="px-6 py-3 text-sm">
                                            <span className={`px-2 py-0.5 rounded text-xs font-semibold ${entry.type === 'CREDIT' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                                                {entry.type === 'CREDIT' ? 'ENTRADA' : 'SAÍDA'}
                                            </span>
                                        </td>
                                        <td className={`px-6 py-3 text-sm font-bold text-right ${entry.type === 'CREDIT' ? 'text-green-600' : 'text-red-500'}`}>
                                            {entry.type === 'CREDIT' ? '+' : '-'} {formatCurrency(entry.amount)}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </div>
            </div>
        </Shell>
    )
}
