import { useQuery } from '@tanstack/react-query'
import { walletApi } from '@/api/wallet'
import { Card } from '@/components/common/Card'
import { formatCurrency, formatDateTime } from '@/utils/formatters'
import { ArrowUpRight, ArrowDownRight } from 'lucide-react'
import { Loading } from '@/components/common/Loading'

export const TransactionHistory = () => {
  const { data: transactions, isLoading } = useQuery({
    queryKey: ['transactions'],
    queryFn: () => walletApi.getTransactions(),
  })

  if (isLoading) return <Loading />

  return (
    <Card>
      <h2 className="text-xl font-bold mb-4">Transaction History</h2>

      <div className="space-y-3">
        {transactions && transactions.length > 0 ? (
          transactions.map((tx) => (
            <div key={tx.id} className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50">
              <div className="flex items-center gap-3">
                <div className={`p-2 rounded-full ${
                  parseFloat(tx.amount) >= 0 ? 'bg-success/10 text-success' : 'bg-error/10 text-error'
                }`}>
                  {parseFloat(tx.amount) >= 0 ? <ArrowDownRight size={20} /> : <ArrowUpRight size={20} />}
                </div>
                <div>
                  <p className="font-medium">{tx.description}</p>
                  <p className="text-sm text-gray-500">{formatDateTime(tx.created_at)}</p>
                </div>
              </div>

              <div className="text-right">
                <p className={`font-semibold ${
                  parseFloat(tx.amount) >= 0 ? 'text-success' : 'text-error'
                }`}>
                  {parseFloat(tx.amount) >= 0 ? '+' : ''}{formatCurrency(tx.amount)}
                </p>
                <p className="text-sm text-gray-500">
                  Balance: {formatCurrency(tx.balance_after)}
                </p>
              </div>
            </div>
          ))
        ) : (
          <p className="text-center text-gray-500 py-8">No transactions yet</p>
        )}
      </div>
    </Card>
  )
}
