import { useState, useEffect } from 'react';
import { CreditCard, Banknote, ArrowRightLeft, DollarSign, X } from 'lucide-react';
import clsx from 'clsx';

// Interfaz de Pago
export interface Payment {
  amount: number;
  paymentMethod: string;
  cardPlan?: string;
  surcharge: number;
}

// Props del Modal de Pagos
interface PaymentModalProps {
  totalAmount: number;
  onConfirm: (payments: Payment[]) => void;
  onCancel: () => void;
}

// Planes de Tarjetas de Crédito con sus recargos
const CARD_PLANS = [
  { value: 'Ahora12', label: 'Ahora 12', surcharge: 15 },
  { value: 'Ahora18', label: 'Ahora 18', surcharge: 20 },
  { value: 'Credit3', label: '3 Cuotas', surcharge: 8 },
  { value: 'Credit6', label: '6 Cuotas', surcharge: 12 },
];

export default function PaymentModal({ totalAmount, onConfirm, onCancel }: PaymentModalProps) {
  // Estado de pagos acumulados
  const [payments, setPayments] = useState<Payment[]>([]);
  const [currentMethod, setCurrentMethod] = useState('Cash');
  const [currentAmount, setCurrentAmount] = useState(totalAmount);
  const [currentPlan, setCurrentPlan] = useState('');

  // Cálculos de totales
  const totalPaid = payments.reduce((sum, p) => sum + p.amount, 0);
  const pendingAmount = totalAmount - totalPaid;

  // Actualizar monto actual cuando cambia el pendiente
  useEffect(() => {
    setCurrentAmount(Math.max(0, pendingAmount));
  }, [pendingAmount]);

  // Agregar un nuevo pago a la lista
  const addPayment = () => {
    if (currentAmount <= 0 || currentAmount > pendingAmount) {
      alert('❌ Monto inválido');
      return;
    }

    if (currentMethod === 'Credit' && !currentPlan) {
      alert('❌ Seleccione un plan de cuotas');
      return;
    }

    const planInfo = CARD_PLANS.find(p => p.value === currentPlan);
    const surcharge = currentMethod === 'Credit' && planInfo ? (currentAmount * planInfo.surcharge) / 100 : 0;

    const newPayment: Payment = {
      amount: currentAmount,
      paymentMethod: currentMethod,
      cardPlan: currentMethod === 'Credit' ? currentPlan : undefined,
      surcharge
    };

    setPayments([...payments, newPayment]);
    setCurrentMethod('Cash');
    setCurrentPlan('');
  };

  // Eliminar un pago de la lista
  const removePayment = (index: number) => {
    setPayments(payments.filter((_, i) => i !== index));
  };

  // Confirmar todos los pagos
  const handleConfirm = () => {
    if (pendingAmount > 0) {
      alert('❌ Aún falta completar el pago');
      return;
    }
    onConfirm(payments);
  };

  // Total incluyendo recargos
  const totalWithSurcharges = payments.reduce((sum, p) => sum + p.amount + p.surcharge, 0);

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-3xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* Encabezado */}
        <div className="sticky top-0 bg-gradient-to-r from-blue-600 to-indigo-600 text-white p-6 rounded-t-3xl">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-black">Procesar Pago</h2>
              <p className="text-sm text-blue-100 mt-1">Configure los medios de pago</p>
            </div>
            <button onClick={onCancel} className="hover:bg-white/20 p-2 rounded-full transition">
              <X size={24} />
            </button>
          </div>
        </div>

        <div className="p-6 space-y-6">
          {/* Resumen de Importes */}
          <div className="grid grid-cols-3 gap-4">
            <div className="bg-blue-50 p-4 rounded-xl border border-blue-200">
              <div className="text-xs text-blue-600 font-bold uppercase mb-1">Total Original</div>
              <div className="text-2xl font-black text-blue-900">${totalAmount.toLocaleString()}</div>
            </div>
            <div className="bg-green-50 p-4 rounded-xl border border-green-200">
              <div className="text-xs text-green-600 font-bold uppercase mb-1">Pagado</div>
              <div className="text-2xl font-black text-green-900">${totalPaid.toLocaleString()}</div>
            </div>
            <div className={clsx("p-4 rounded-xl border", pendingAmount > 0 ? "bg-orange-50 border-orange-200" : "bg-gray-50 border-gray-200")}>
              <div className={clsx("text-xs font-bold uppercase mb-1", pendingAmount > 0 ? "text-orange-600" : "text-gray-500")}>Pendiente</div>
              <div className={clsx("text-2xl font-black", pendingAmount > 0 ? "text-orange-900" : "text-gray-400")}>${pendingAmount.toLocaleString()}</div>
            </div>
          </div>

          {/* Lista de Pagos Agregados */}
          {payments.length > 0 && (
            <div className="space-y-2">
              <h3 className="text-sm font-bold text-gray-600 uppercase">Pagos Agregados</h3>
              {payments.map((payment, index) => (
                <div key={index} className="flex items-center justify-between bg-gray-50 p-3 rounded-lg border border-gray-200">
                  <div className="flex items-center gap-3">
                    {payment.paymentMethod === 'Cash' && <Banknote className="text-green-600" size={20} />}
                    {payment.paymentMethod === 'Debit' && <CreditCard className="text-blue-600" size={20} />}
                    {payment.paymentMethod === 'Credit' && <CreditCard className="text-purple-600" size={20} />}
                    {payment.paymentMethod === 'Transfer' && <ArrowRightLeft className="text-indigo-600" size={20} />}
                    <div>
                      <div className="font-bold text-sm">
                        {payment.paymentMethod === 'Cash' && 'Efectivo'}
                        {payment.paymentMethod === 'Debit' && 'Débito'}
                        {payment.paymentMethod === 'Credit' && payment.cardPlan}
                        {payment.paymentMethod === 'Transfer' && 'Transferencia'}
                      </div>
                      {payment.surcharge > 0 && (
                        <div className="text-xs text-orange-600">+${payment.surcharge.toLocaleString()} recargo</div>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <span className="font-black text-lg">${payment.amount.toLocaleString()}</span>
                    <button onClick={() => removePayment(index)} className="text-red-500 hover:bg-red-50 p-1 rounded">
                      <X size={18} />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Formulario para Agregar Pago */}
          {pendingAmount > 0 && (
            <div className="border-2 border-dashed border-gray-300 rounded-xl p-4 space-y-4">
              <h3 className="text-sm font-bold text-gray-600 uppercase">Agregar Pago</h3>

              {/* Selector de Método de Pago */}
              <div className="grid grid-cols-4 gap-2">
                {[
                  { value: 'Cash', label: 'Efectivo', icon: Banknote, color: 'green' },
                  { value: 'Debit', label: 'Débito', icon: CreditCard, color: 'blue' },
                  { value: 'Credit', label: 'Crédito', icon: CreditCard, color: 'purple' },
                  { value: 'Transfer', label: 'Transferencia', icon: ArrowRightLeft, color: 'indigo' }
                ].map((method) => (
                  <button
                    key={method.value}
                    onClick={() => setCurrentMethod(method.value)}
                    className={clsx(
                      "p-3 rounded-lg border-2 transition-all flex flex-col items-center gap-1",
                      currentMethod === method.value
                        ? `border-${method.color}-600 bg-${method.color}-50`
                        : "border-gray-200 hover:border-gray-300"
                    )}
                  >
                    <method.icon size={20} className={currentMethod === method.value ? `text-${method.color}-600` : 'text-gray-400'} />
                    <span className="text-xs font-bold">{method.label}</span>
                  </button>
                ))}
              </div>

              {/* Selector de Plan de Cuotas (solo para Crédito) */}
              {currentMethod === 'Credit' && (
                <div>
                  <label className="block text-xs font-bold text-gray-600 uppercase mb-2">Plan de Cuotas</label>
                  <select
                    value={currentPlan}
                    onChange={(e) => setCurrentPlan(e.target.value)}
                    className="w-full p-3 border border-gray-300 rounded-lg font-bold"
                  >
                    <option value="">-- Seleccionar Plan --</option>
                    {CARD_PLANS.map(plan => (
                      <option key={plan.value} value={plan.value}>
                        {plan.label} (+{plan.surcharge}% recargo)
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {/* Input de Monto */}
              <div>
                <label className="block text-xs font-bold text-gray-600 uppercase mb-2">Monto</label>
                <div className="relative">
                  <DollarSign className="absolute left-3 top-3 text-gray-400" size={20} />
                  <input
                    type="number"
                    value={currentAmount}
                    onChange={(e) => setCurrentAmount(parseFloat(e.target.value) || 0)}
                    className="w-full pl-10 p-3 border border-gray-300 rounded-lg font-black text-xl"
                    max={pendingAmount}
                  />
                </div>
              </div>

              <button
                onClick={addPayment}
                className="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-black uppercase transition"
              >
                + Agregar Pago
              </button>
            </div>
          )}

          {/* Resumen Final con Recargos */}
          {totalWithSurcharges !== totalAmount && (
            <div className="bg-orange-50 border border-orange-200 p-4 rounded-lg">
              <div className="flex justify-between items-center">
                <span className="text-sm font-bold text-orange-700">Total con Recargos</span>
                <span className="text-2xl font-black text-orange-900">${totalWithSurcharges.toLocaleString()}</span>
              </div>
            </div>
          )}
        </div>

        {/* Botones de Acción */}
        <div className="sticky bottom-0 bg-gray-50 p-6 rounded-b-3xl border-t border-gray-200 flex gap-3">
          <button
            onClick={onCancel}
            className="flex-1 bg-white border-2 border-gray-300 text-gray-700 py-4 rounded-xl font-black uppercase hover:bg-gray-100 transition"
          >
            Cancelar
          </button>
          <button
            onClick={handleConfirm}
            disabled={pendingAmount > 0}
            className={clsx(
              "flex-1 py-4 rounded-xl font-black uppercase transition",
              pendingAmount > 0
                ? "bg-gray-300 text-gray-500 cursor-not-allowed"
                : "bg-green-600 hover:bg-green-700 text-white"
            )}
          >
            {pendingAmount > 0 ? 'Completar Pagos' : 'Confirmar Cobro'}
          </button>
        </div>
      </div>
    </div>
  );
}

