/**
 * WalletCard Component
 * Displays wallet balance and recent transactions
 */

import React from 'react';
import {
  Wallet,
  ArrowUpCircle,
  ArrowDownCircle,
  Gift,
  RefreshCw,
  ShoppingCart,
  ChevronRight,
} from 'lucide-react';
import type { Wallet as WalletType, WalletTransaction, TransactionType } from '../../types/payment.types';

interface WalletCardProps {
  wallet: WalletType;
  recentTransactions?: WalletTransaction[];
  onDeposit?: () => void;
  onWithdraw?: () => void;
  onViewHistory?: () => void;
  loading?: boolean;
}

const transactionIcons: Record<TransactionType, React.ReactNode> = {
  deposit: <ArrowDownCircle className="w-5 h-5 text-green-400" />,
  withdrawal: <ArrowUpCircle className="w-5 h-5 text-red-400" />,
  transfer_in: <ArrowDownCircle className="w-5 h-5 text-blue-400" />,
  transfer_out: <ArrowUpCircle className="w-5 h-5 text-blue-400" />,
  fee: <ShoppingCart className="w-5 h-5 text-orange-400" />,
  refund: <RefreshCw className="w-5 h-5 text-blue-400" />,
  earning: <ArrowDownCircle className="w-5 h-5 text-green-400" />,
  distribution: <ArrowDownCircle className="w-5 h-5 text-green-400" />,
  bonus: <Gift className="w-5 h-5 text-yellow-400" />,
  reward: <Gift className="w-5 h-5 text-purple-400" />,
  purchase: <ShoppingCart className="w-5 h-5 text-orange-400" />,
};

const transactionLabels: Record<TransactionType, string> = {
  deposit: 'Depósito',
  withdrawal: 'Retiro',
  transfer_in: 'Transferencia Recibida',
  transfer_out: 'Transferencia Enviada',
  fee: 'Comisión',
  refund: 'Reembolso',
  earning: 'Ganancia',
  distribution: 'Distribución',
  bonus: 'Bono',
  reward: 'Recompensa',
  purchase: 'Compra',
};

export const WalletCard: React.FC<WalletCardProps> = ({
  wallet,
  recentTransactions = [],
  onDeposit,
  onWithdraw,
  onViewHistory,
  loading = false,
}) => {
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: wallet.currency,
    }).format(amount);
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (hours < 1) return 'Hace unos minutos';
    if (hours < 24) return `Hace ${hours}h`;
    if (days < 7) return `Hace ${days} días`;
    return date.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' });
  };

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
      {/* Balance Section */}
      <div className="p-6 bg-gradient-to-br from-blue-600/20 to-purple-600/20">
        <div className="flex items-center gap-3 mb-4">
          <div className="p-3 bg-blue-500/20 rounded-xl">
            <Wallet className="w-6 h-6 text-blue-400" />
          </div>
          <div>
            <p className="text-sm text-gray-400">Saldo Disponible</p>
            <h2 className="text-3xl font-bold text-white">
              {formatCurrency(wallet.availableBalance)}
            </h2>
          </div>
        </div>

        {/* Balance Details */}
        <div className="grid grid-cols-2 gap-4 mt-4">
          <div className="p-3 bg-gray-900/50 rounded-lg">
            <p className="text-xs text-gray-500">Pendiente</p>
            <p className="text-lg font-semibold text-yellow-400">
              {formatCurrency(wallet.pendingBalance)}
            </p>
          </div>
          <div className="p-3 bg-gray-900/50 rounded-lg">
            <p className="text-xs text-gray-500">Total en cuenta</p>
            <p className="text-lg font-semibold text-white">
              {formatCurrency(wallet.balance)}
            </p>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex gap-3 mt-6">
          <button
            onClick={onDeposit}
            disabled={loading}
            className="flex-1 flex items-center justify-center gap-2 py-3 bg-green-600 hover:bg-green-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50"
          >
            <ArrowDownCircle className="w-5 h-5" />
            Depositar
          </button>
          <button
            onClick={onWithdraw}
            disabled={loading || wallet.availableBalance <= 0}
            className="flex-1 flex items-center justify-center gap-2 py-3 bg-gray-700 hover:bg-gray-600 text-white rounded-lg font-medium transition-colors disabled:opacity-50"
          >
            <ArrowUpCircle className="w-5 h-5" />
            Retirar
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="p-4 bg-gray-900/30 border-y border-gray-700 grid grid-cols-2 gap-4">
        <div className="text-center">
          <p className="text-xs text-gray-500">Total Depositado</p>
          <p className="text-sm font-medium text-green-400">
            {formatCurrency(wallet.totalDeposited)}
          </p>
        </div>
        <div className="text-center">
          <p className="text-xs text-gray-500">Total Retirado</p>
          <p className="text-sm font-medium text-red-400">
            {formatCurrency(wallet.totalWithdrawn)}
          </p>
        </div>
      </div>

      {/* Recent Transactions */}
      <div className="p-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-medium text-white">Transacciones Recientes</h3>
          {onViewHistory && (
            <button
              onClick={onViewHistory}
              className="text-sm text-blue-400 hover:text-blue-300 flex items-center gap-1"
            >
              Ver todo
              <ChevronRight className="w-4 h-4" />
            </button>
          )}
        </div>

        {recentTransactions.length > 0 ? (
          <div className="space-y-3">
            {recentTransactions.slice(0, 5).map((tx) => (
              <div
                key={tx.id}
                className="flex items-center justify-between p-3 bg-gray-900/50 rounded-lg"
              >
                <div className="flex items-center gap-3">
                  {transactionIcons[tx.type]}
                  <div>
                    <p className="text-sm font-medium text-white">
                      {tx.description || transactionLabels[tx.type]}
                    </p>
                    <p className="text-xs text-gray-500">{formatDate(tx.createdAt)}</p>
                  </div>
                </div>
                <div className="text-right">
                  <p
                    className={`font-medium ${
                      tx.type === 'withdrawal' || tx.type === 'purchase' || tx.type === 'transfer_out' || tx.type === 'fee'
                        ? 'text-red-400'
                        : 'text-green-400'
                    }`}
                  >
                    {tx.type === 'withdrawal' || tx.type === 'purchase' || tx.type === 'transfer_out' || tx.type === 'fee' ? '-' : '+'}
                    {formatCurrency(tx.amount)}
                  </p>
                  <p className="text-xs text-gray-500">
                    Saldo: {formatCurrency(tx.balanceAfter)}
                  </p>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <Wallet className="w-12 h-12 mx-auto mb-2 opacity-50" />
            <p>No hay transacciones recientes</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default WalletCard;
