/**
 * WalletDepositModal Component
 * Modal for depositing funds to wallet
 */

import React, { useState, useEffect } from 'react';
import { X, CreditCard, Loader2, AlertCircle, CheckCircle } from 'lucide-react';
import { usePaymentStore } from '../../stores/paymentStore';
import { depositToWallet } from '../../services/payment.service';

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

const PRESET_AMOUNTS = [50, 100, 250, 500, 1000];

export const WalletDepositModal: React.FC<WalletDepositModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  currency = 'USD',
}) => {
  const { paymentMethods, fetchPaymentMethods, loadingPaymentMethods } = usePaymentStore();
  const [amount, setAmount] = useState<string>('100');
  const [selectedMethod, setSelectedMethod] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  useEffect(() => {
    if (isOpen) {
      fetchPaymentMethods();
      setAmount('100');
      setError(null);
      setSuccess(false);
    }
  }, [isOpen, fetchPaymentMethods]);

  useEffect(() => {
    // Auto-select default payment method
    if (paymentMethods.length > 0 && !selectedMethod) {
      const defaultMethod = paymentMethods.find((m) => m.isDefault) || paymentMethods[0];
      setSelectedMethod(defaultMethod.id);
    }
  }, [paymentMethods, selectedMethod]);

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

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

    if (!selectedMethod) {
      setError('Selecciona un metodo de pago');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      await depositToWallet(numAmount, selectedMethod);
      setSuccess(true);
      setTimeout(() => {
        onSuccess?.();
        onClose();
      }, 2000);
    } catch (err) {
      setError('Error al procesar el deposito. Intenta de nuevo.');
      console.error('Deposit error:', err);
    } finally {
      setLoading(false);
    }
  };

  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">Depositar 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">Deposito Exitoso</h3>
            <p className="text-gray-400">
              Se han agregado ${parseFloat(amount).toFixed(2)} a tu wallet
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="p-4 space-y-4">
            {/* Amount Input */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Monto a depositar</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"
                  step="0.01"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  className="w-full pl-8 pr-16 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"
                />
                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500">
                  {currency}
                </span>
              </div>
            </div>

            {/* Preset Amounts */}
            <div className="flex flex-wrap gap-2">
              {PRESET_AMOUNTS.map((preset) => (
                <button
                  key={preset}
                  type="button"
                  onClick={() => setAmount(String(preset))}
                  className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                    amount === String(preset)
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                  }`}
                >
                  ${preset}
                </button>
              ))}
            </div>

            {/* Payment Method Selection */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Metodo de pago</label>
              {loadingPaymentMethods ? (
                <div className="flex items-center justify-center py-4">
                  <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
                </div>
              ) : paymentMethods.length > 0 ? (
                <div className="space-y-2">
                  {paymentMethods.map((method) => (
                    <label
                      key={method.id}
                      className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-colors ${
                        selectedMethod === method.id
                          ? 'bg-blue-600/20 border border-blue-500'
                          : 'bg-gray-700 border border-transparent hover:bg-gray-600'
                      }`}
                    >
                      <input
                        type="radio"
                        name="paymentMethod"
                        value={method.id}
                        checked={selectedMethod === method.id}
                        onChange={(e) => setSelectedMethod(e.target.value)}
                        className="sr-only"
                      />
                      <CreditCard className="w-5 h-5 text-gray-400" />
                      <div className="flex-1">
                        <p className="text-white font-medium">
                          {method.brand} **** {method.last4}
                        </p>
                        {method.expiryMonth && method.expiryYear && (
                          <p className="text-xs text-gray-500">
                            Expira {method.expiryMonth}/{method.expiryYear}
                          </p>
                        )}
                      </div>
                      {method.isDefault && (
                        <span className="text-xs text-blue-400">Default</span>
                      )}
                    </label>
                  ))}
                </div>
              ) : (
                <div className="text-center py-4 bg-gray-700 rounded-lg">
                  <p className="text-gray-400 text-sm mb-2">No tienes metodos de pago guardados</p>
                  <button
                    type="button"
                    onClick={() => window.location.href = '/settings/billing'}
                    className="text-blue-400 text-sm hover:text-blue-300"
                  >
                    Agregar metodo de pago
                  </button>
                </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>
            )}

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading || !selectedMethod || paymentMethods.length === 0}
              className="w-full py-3 bg-green-600 hover:bg-green-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...
                </>
              ) : (
                <>Depositar ${parseFloat(amount || '0').toFixed(2)}</>
              )}
            </button>

            <p className="text-xs text-gray-500 text-center">
              Los depositos se procesan de forma segura a traves de Stripe
            </p>
          </form>
        )}
      </div>
    </div>
  );
};

export default WalletDepositModal;
