/**
 * WalletWithdrawModal Component
 * Modal for withdrawing funds from wallet
 */

import React, { useState } from 'react';
import { X, Building2, Loader2, AlertCircle, CheckCircle, AlertTriangle } from 'lucide-react';
import { withdrawFromWallet } from '../../services/payment.service';

interface WalletWithdrawModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  availableBalance: number;
  currency?: string;
}

export const WalletWithdrawModal: React.FC<WalletWithdrawModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  availableBalance,
  currency = 'USD',
}) => {
  const [amount, setAmount] = useState<string>('');
  const [bankAccount, setBankAccount] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const numAmount = parseFloat(amount);

    if (isNaN(numAmount) || numAmount < 10) {
      setError('El monto minimo de retiro es $10');
      return;
    }

    if (numAmount > availableBalance) {
      setError('El monto excede tu saldo disponible');
      return;
    }

    if (!bankAccount.trim()) {
      setError('Ingresa el ID de tu cuenta bancaria');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      await withdrawFromWallet(numAmount, {
        type: 'bank_account',
        accountId: bankAccount.trim(),
      });
      setSuccess(true);
      setTimeout(() => {
        onSuccess?.();
        onClose();
      }, 2000);
    } catch (err) {
      setError('Error al procesar el retiro. Verifica los datos e intenta de nuevo.');
      console.error('Withdrawal error:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleMaxAmount = () => {
    setAmount(String(availableBalance));
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
      <div className="bg-gray-800 rounded-xl w-full max-w-md overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-700">
          <h2 className="text-lg font-semibold text-white">Retirar Fondos</h2>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-white rounded-lg hover:bg-gray-700 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {success ? (
          <div className="p-8 text-center">
            <div className="w-16 h-16 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-8 h-8 text-green-400" />
            </div>
            <h3 className="text-xl font-semibold text-white mb-2">Retiro Solicitado</h3>
            <p className="text-gray-400">
              Tu retiro de ${parseFloat(amount).toFixed(2)} esta siendo procesado
            </p>
            <p className="text-sm text-gray-500 mt-2">
              El tiempo de procesamiento es de 1-3 dias habiles
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="p-4 space-y-4">
            {/* Available Balance */}
            <div className="p-4 bg-gray-900/50 rounded-lg">
              <p className="text-sm text-gray-400 mb-1">Saldo disponible</p>
              <p className="text-2xl font-bold text-white">
                ${availableBalance.toFixed(2)} {currency}
              </p>
            </div>

            {/* Amount Input */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Monto a retirar</label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">$</span>
                <input
                  type="number"
                  min="10"
                  max={availableBalance}
                  step="0.01"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  className="w-full pl-8 pr-20 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white text-lg font-medium focus:outline-none focus:border-blue-500"
                  placeholder="0.00"
                />
                <button
                  type="button"
                  onClick={handleMaxAmount}
                  className="absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 bg-gray-700 hover:bg-gray-600 text-sm text-gray-300 rounded transition-colors"
                >
                  MAX
                </button>
              </div>
            </div>

            {/* Bank Account */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Cuenta bancaria destino</label>
              <div className="relative">
                <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  value={bankAccount}
                  onChange={(e) => setBankAccount(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-blue-500"
                  placeholder="ID de cuenta bancaria"
                />
              </div>
              <p className="text-xs text-gray-500 mt-1">
                Puedes configurar tus cuentas bancarias en el portal de Stripe
              </p>
            </div>

            {/* Warning */}
            <div className="flex items-start gap-2 p-3 bg-yellow-900/20 border border-yellow-800/50 rounded-lg">
              <AlertTriangle className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-yellow-400/80">
                <p className="font-medium">Importante:</p>
                <ul className="list-disc list-inside mt-1 space-y-1 text-xs">
                  <li>Los retiros tardan 1-3 dias habiles en procesarse</li>
                  <li>Se aplicara una comision del 1% (min $1)</li>
                  <li>El monto minimo de retiro es $10</li>
                </ul>
              </div>
            </div>

            {/* Error Message */}
            {error && (
              <div className="flex items-center gap-2 p-3 bg-red-900/20 border border-red-800 rounded-lg">
                <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
                <p className="text-sm text-red-400">{error}</p>
              </div>
            )}

            {/* Summary */}
            {amount && parseFloat(amount) >= 10 && (
              <div className="p-3 bg-gray-700 rounded-lg space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-400">Monto</span>
                  <span className="text-white">${parseFloat(amount).toFixed(2)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-400">Comision (1%)</span>
                  <span className="text-red-400">
                    -${Math.max(parseFloat(amount) * 0.01, 1).toFixed(2)}
                  </span>
                </div>
                <div className="flex justify-between pt-2 border-t border-gray-600">
                  <span className="text-gray-300 font-medium">Recibiras</span>
                  <span className="text-green-400 font-bold">
                    ${(parseFloat(amount) - Math.max(parseFloat(amount) * 0.01, 1)).toFixed(2)}
                  </span>
                </div>
              </div>
            )}

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading || !amount || parseFloat(amount) < 10 || parseFloat(amount) > availableBalance}
              className="w-full py-3 bg-red-600 hover:bg-red-500 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Procesando...
                </>
              ) : (
                <>Solicitar Retiro</>
              )}
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

export default WalletWithdrawModal;
