import { useState } from 'react';
import { useWizardStore } from '../../store/wizardStore';
import { wizardService } from '../../services/wizardService';
import { StepWrapper } from '../../components/StepWrapper';
import type { AttributeDefinition } from '../../types';
import {
  CreditCard,
  Wallet,
  ChevronRight,
  ArrowLeft,
  Tag,
  FileText,
  Clock
} from 'lucide-react';
import { initMercadoPago, Wallet as MPWallet } from '@mercadopago/sdk-react';
import clsx from 'clsx';
import api from '../../services/api';

// Se inicializa con la Public Key desde env
initMercadoPago(import.meta.env.VITE_MP_PUBLIC_KEY);

export default function SummaryStep({ definitions }: { definitions: AttributeDefinition[] }) {
  const { selectedCategory, selectedOperation, attributes, photos, setStep, reset } = useWizardStore();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [preferenceId, setPreferenceId] = useState<string | null>(null);
  const [createdId, setCreatedId] = useState<number | null>(null);
  const [paymentMethod, setPaymentMethod] = useState<'mercadopago' | 'stripe'>('mercadopago');

  const adFee = parseFloat(attributes['adFee'] || "0");
  const listingPrice = parseFloat(attributes['price'] || "0");

  const handlePublish = async () => {
    if (!selectedCategory || !selectedOperation) return;

    setIsSubmitting(true);
    try {
      const attributePayload: Record<number, string> = {};
      const { existingImages } = useWizardStore.getState();

      definitions.forEach(def => {
        const val = attributes[def.name.toLowerCase()] || attributes[def.name];
        if (val) {
          attributePayload[def.id] = val.toString();
        }
      });

      const payload = {
        categoryId: selectedCategory.id,
        operationId: selectedOperation.id,
        title: attributes['title'],
        description: attributes['description'],
        price: parseFloat(attributes['price'] || "0"),
        adFee: adFee,
        currency: 'ARS',
        status: 'Pending',
        origin: 'Web',
        attributes: attributePayload,
        imagesToClone: existingImages.map(img => img.url),
        printText: attributes['description'],
        printDaysCount: parseInt(attributes['days'] || "3"),
        isBold: false,
        isFrame: false,
        printFontSize: 'normal',
        printAlignment: 'left',
        publicationStartDate: attributes['publicationStartDate'],
        isFeatured: attributes['isFeatured'] === 'true',
        allowContact: attributes['allowContact'] === 'true',
        couponCode: attributes['couponCode']
      };

      const result = await wizardService.createListing(payload);
      setCreatedId(result.id);

      if (photos.length > 0) {
        for (const photo of photos) {
          await wizardService.uploadImage(result.id, photo);
        }
      }

      const resp = await fetch(`${import.meta.env.VITE_API_URL}/payments/create-preference/${result.id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(adFee)
      });
      const data = await resp.json();

      if (data.id) {
        setPreferenceId(data.id);
      }
    } catch (error) {
      console.error(error);
      alert('Error al publicar');
    } finally {
      setIsSubmitting(false);
    }
  };

  const urlParams = new URLSearchParams(window.location.search);
  const paymentStatus = urlParams.get('status');

  if (paymentStatus === 'approved') {
    return (
      <StepWrapper>
        <div className="text-center py-20 bg-white rounded-[3rem] shadow-2xl p-12 border border-emerald-100">
          <div className="w-24 h-24 bg-blue-50 text-blue-500 rounded-full flex items-center justify-center mx-auto mb-8 shadow-inner">
            <Clock size={64} strokeWidth={1.5} className="animate-pulse" />
          </div>
          <h2 className="text-4xl font-black mb-4 text-slate-900 tracking-tighter uppercase">¡Pago Recibido!</h2>
          <p className="text-slate-500 text-lg mb-10 font-medium max-w-md mx-auto">
            Tu aviso ha sido enviado a nuestro equipo de **Moderación**. Una vez aprobado, se publicará automáticamente en el portal y en la edición impresa.
          </p>
          <div className="flex flex-col gap-3 max-w-xs mx-auto">
            <button
              onClick={() => { reset(); window.location.href = '/profile'; }}
              className="bg-slate-900 text-white px-12 py-5 rounded-2xl font-black uppercase text-xs tracking-[0.2em] hover:bg-black transition-all shadow-xl shadow-slate-200"
            >
              Ver estado en mi Perfil
            </button>
          </div>
        </div>
      </StepWrapper>
    );
  }

  if (preferenceId) {
    return (
      <StepWrapper>
        <div className="text-center py-20 bg-white rounded-[3rem] shadow-2xl p-12 border border-blue-100">
          <div className="w-24 h-24 bg-blue-50 text-blue-600 rounded-full flex items-center justify-center mx-auto mb-8">
            <Wallet size={56} strokeWidth={1.5} />
          </div>
          <h2 className="text-3xl font-black mb-4 text-slate-900 tracking-tighter uppercase">Finalizar Publicación</h2>

          {/* LÓGICA DE SIMULACIÓN */}
          {preferenceId === "MOCK_PREFERENCE_ID_12345" ? (
            <div className="space-y-6">
              <div className="p-4 bg-amber-50 border border-amber-100 rounded-2xl text-amber-700 text-xs font-bold uppercase">
                Modo Simulación Activo: Token de MP no configurado.
              </div>
              <p className="text-slate-500 text-sm mb-8 font-medium max-w-sm mx-auto">
                Estás en el entorno de desarrollo. Haz clic abajo para simular un pago aprobado y finalizar el proceso.
              </p>
              <button
                onClick={async () => {
                  try {
                    // Enviamos un objeto en lugar del número solo
                    await api.post(`/payments/confirm-simulation/${createdId}`, {
                      amount: adFee
                    });

                    // Si la petición es exitosa, procedemos a la pantalla de éxito
                    window.location.href = window.location.pathname + '?status=approved';
                  } catch (error) {
                    console.error("Error en la simulación:", error);
                    alert("No se pudo confirmar el pago simulado.");
                  }
                }}
                className="w-full py-5 bg-emerald-500 hover:bg-emerald-600 text-white rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl shadow-emerald-200 transition-all"
              >
                Simular Pago Aprobado
              </button>
            </div>
          ) : (
            // LÓGICA REAL
            <>
              <p className="text-slate-500 text-lg mb-10 font-medium max-w-sm mx-auto leading-tight">
                Haz clic abajo para completar el pago de <strong>${adFee.toLocaleString()}</strong> de forma segura con Mercado Pago.
              </p>
              <div className="max-w-xs mx-auto scale-110">
                <MPWallet initialization={{ preferenceId }} />
              </div>
            </>
          )}
        </div>
      </StepWrapper>
    );
  }

  return (
    <StepWrapper>
      <div className="mb-10 text-center">
        <span className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-400 mb-4 block">Paso Final</span>
        <h2 className="text-4xl font-black text-slate-900 tracking-tighter uppercase leading-none">
          Resumen de <br />
          <span className="text-blue-600">tu publicación</span>
        </h2>
      </div>

      <div className="max-w-2xl mx-auto space-y-8">

        {/* RESUMEN DEL AVISO */}
        <section className="bg-white p-8 rounded-[2.5rem] shadow-2xl shadow-slate-200/50 border border-slate-100">
          <div className="flex justify-between items-start mb-8 pb-6 border-b border-slate-50">
            <div className="flex items-center gap-4">
              <div className="p-3 bg-slate-50 rounded-2xl text-slate-400"><FileText size={20} /></div>
              <div>
                <h3 className="font-black text-slate-900 uppercase text-sm tracking-tight">{attributes['title']}</h3>
                <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{selectedCategory?.name} / {selectedOperation?.name}</p>
              </div>
            </div>
            <div className="text-right">
              <span className="text-[9px] font-black text-slate-400 uppercase block mb-1">Precio Producto</span>
              <p className="text-xl font-black text-slate-900">${listingPrice.toLocaleString()}</p>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-x-10 gap-y-4 mb-4">
            {definitions.map(def => {
              const val = attributes[def.name.toLowerCase()] || attributes[def.name];
              return val && (
                <div key={def.id} className="flex justify-between items-center group">
                  <span className="text-[10px] font-bold text-slate-400 uppercase group-hover:text-slate-600 transition-colors">{def.name}</span>
                  <span className="text-xs font-black text-slate-800 uppercase">{val}</span>
                </div>
              );
            })}
          </div>
        </section>

        {/* --- BLOQUE DE COSTO (TOTAL A PAGAR) --- */}
        <section className="bg-blue-600 rounded-[2.5rem] p-8 text-white shadow-2xl shadow-blue-200 relative overflow-hidden">
          <div className="flex justify-between items-center relative z-10">
            <div>
              <span className="text-[10px] font-black uppercase tracking-[0.3em] opacity-60">Total a Pagar</span>
              <div className="flex items-baseline gap-2 mt-1">
                <span className="text-xl font-black">$</span>
                <span className="text-5xl font-black font-mono tracking-tighter">
                  {adFee.toLocaleString('es-AR', { minimumFractionDigits: 2 })}
                </span>
              </div>
            </div>
            <div className="bg-white/10 p-4 rounded-[1.5rem] border border-white/20 backdrop-blur-sm">
              <Tag size={24} className="text-white" />
            </div>
          </div>
        </section>

        {/* MÉTODO DE PAGO */}
        <section className="space-y-4">
          <h3 className="text-xs font-black text-slate-400 uppercase tracking-widest ml-4">Selecciona Método de Pago</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <label className={clsx(
              "flex items-center gap-4 p-6 rounded-3xl border-2 cursor-pointer transition-all",
              paymentMethod === 'mercadopago' ? "border-blue-600 bg-blue-50 shadow-lg shadow-blue-100" : "border-slate-100 bg-white hover:border-blue-200"
            )}>
              <input type="radio" className="hidden" checked={paymentMethod === 'mercadopago'} onChange={() => setPaymentMethod('mercadopago')} />
              <div className={clsx("p-3 rounded-2xl", paymentMethod === 'mercadopago' ? "bg-blue-600 text-white" : "bg-slate-100 text-slate-400")}>
                <Wallet size={24} />
              </div>
              <div>
                <p className="font-black text-slate-900 uppercase text-xs">Mercado Pago</p>
                <p className="text-[10px] text-slate-400 font-bold uppercase">QR, Débito, Crédito</p>
              </div>
            </label>

            <label className={clsx(
              "flex items-center gap-4 p-6 rounded-3xl border-2 cursor-pointer transition-all",
              paymentMethod === 'stripe' ? "border-slate-900 bg-slate-50 shadow-lg shadow-slate-100" : "border-slate-100 bg-white hover:border-slate-200"
            )}>
              <input type="radio" className="hidden" checked={paymentMethod === 'stripe'} onChange={() => setPaymentMethod('stripe')} />
              <div className={clsx("p-3 rounded-2xl", paymentMethod === 'stripe' ? "bg-slate-900 text-white" : "bg-slate-100 text-slate-400")}>
                <CreditCard size={24} />
              </div>
              <div>
                <p className="font-black text-slate-900 uppercase text-xs">Tarjeta Directa</p>
                <p className="text-[10px] text-slate-400 font-bold uppercase">Visa o MasterCard</p>
              </div>
            </label>
          </div>
        </section>

        {/* ACCIÓN PRINCIPAL */}
        <div className="flex flex-col md:flex-row gap-4 pt-6">
          <button
            onClick={() => setStep(5)}
            className="flex-1 py-5 bg-slate-100 text-slate-500 font-black uppercase text-xs tracking-widest rounded-2xl hover:bg-slate-200 transition-all flex items-center justify-center gap-3"
            disabled={isSubmitting}
          >
            <ArrowLeft size={16} /> Volver
          </button>
          <button
            onClick={handlePublish}
            disabled={isSubmitting}
            className="flex-[2] py-5 bg-blue-600 text-white font-black uppercase text-xs tracking-[0.2em] rounded-2xl shadow-xl shadow-blue-500/20 hover:bg-blue-700 disabled:opacity-50 transition-all flex items-center justify-center gap-3 group"
          >
            <span className="text-white">
              {isSubmitting ? 'Procesando...' : 'Pagar y Publicar Aviso'}
            </span>
            <ChevronRight size={18} className="text-blue-300 group-hover:translate-x-1 transition-transform" />
          </button>
        </div>
      </div>
    </StepWrapper>
  );
}