import { useState, useEffect } from 'react';
import { useWizardStore } from '../../store/wizardStore';
import { StepWrapper } from '../../components/StepWrapper';
import { useDebounce } from '../../hooks/useDebounce';
import { Eye, FileText, Calendar, ChevronRight, ArrowLeft } from 'lucide-react';
import clsx from 'clsx';
import api from '../../services/api';

interface PricingResult {
  totalPrice: number;
  baseCost: number;
  extraCost: number;
  wordCount: number;
  specialCharCount: number;
  details: string;
  discount: number;
}

export default function TextEditorStep() {
  const { selectedCategory, attributes, setAttribute, setStep } = useWizardStore();
  const [text, setText] = useState(attributes['description'] || '');
  const [days, setDays] = useState(parseInt(attributes['days'] as string) || 3);
  const [startDate, setStartDate] = useState<Date>(new Date());
  const [isFeatured, setIsFeatured] = useState<boolean>(false);
  const [allowContact, setAllowContact] = useState<boolean>(true);
  const [couponCode, setCouponCode] = useState<string>('');

  const [pricing, setPricing] = useState<PricingResult>({
    totalPrice: 0,
    baseCost: 0,
    extraCost: 0,
    wordCount: 0,
    specialCharCount: 0,
    details: '',
    discount: 0
  });
  const [loadingPrice, setLoadingPrice] = useState(false);

  const debouncedText = useDebounce(text, 800);
  const debouncedCoupon = useDebounce(couponCode, 800);

  useEffect(() => {
    if (!selectedCategory || debouncedText.length === 0) {
      setPricing({ totalPrice: 0, baseCost: 0, extraCost: 0, wordCount: 0, specialCharCount: 0, details: '', discount: 0 });
      return;
    }

    const calculatePrice = async () => {
      setLoadingPrice(true);
      try {
        const response = await api.post('/pricing/calculate', {
          categoryId: selectedCategory.id,
          text: debouncedText,
          days: days,
          isBold: false, // Could expose this too
          isFrame: false, // Could expose this too
          isFeatured: isFeatured,
          startDate: startDate.toISOString(),
          couponCode: debouncedCoupon
        });
        setPricing(response.data);
      } catch (error) {
        console.error('Error al calcular precio:', error);
      } finally {
        setLoadingPrice(false);
      }
    };

    calculatePrice();
  }, [debouncedText, days, selectedCategory, isFeatured, startDate, debouncedCoupon]);

  const handleContinue = () => {
    if (text.trim().length === 0) {
      alert('⚠️ Debes escribir el texto del aviso');
      return;
    }
    setAttribute('description', text);
    setAttribute('days', days.toString());
    setAttribute('adFee', pricing.totalPrice.toString());
    setAttribute('publicationStartDate', startDate.toISOString());
    setAttribute('allowContact', allowContact.toString());
    setAttribute('isFeatured', isFeatured.toString());
    setAttribute('couponCode', couponCode);
    setStep(5); // Siguiente paso
  };

  return (
    <StepWrapper>
      {/* Header & Breadcrumb */}
      <div className="mb-10 text-center">
        <div className="flex justify-center items-center gap-2 text-[10px] font-black uppercase tracking-[0.3em] text-slate-400 mb-4">
          <span>{selectedCategory?.name}</span>
          <ChevronRight size={12} />
          <span className="text-blue-600">Redacción</span>
        </div>
        <h2 className="text-4xl font-black text-slate-900 tracking-tighter uppercase leading-none">
          Escribe tu <br />
          <span className="text-blue-600">Aviso Clasificado</span>
        </h2>
      </div>

      <div className="max-w-3xl mx-auto space-y-10">

        {/* BLOQUE 1: EL EDITOR */}
        <section className="bg-white p-8 rounded-[2.5rem] shadow-2xl shadow-slate-200/50 border border-slate-100">
          <div className="flex items-center gap-3 mb-6 text-slate-900">
            <div className="p-2 bg-blue-50 rounded-xl text-blue-600">
              <FileText size={20} />
            </div>
            <h3 className="font-black uppercase tracking-widest text-xs">Contenido del Aviso</h3>
          </div>

          <textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            className="w-full h-56 p-6 bg-slate-50 border-2 border-slate-100 rounded-[2rem] outline-none focus:border-blue-500 focus:bg-white transition-all font-mono text-lg leading-relaxed text-slate-700 placeholder:text-slate-300"
            placeholder="Comienza a escribir aquí..."
          />

          <div className="flex justify-between items-center mt-6 px-2">
            <div className="flex gap-6">
              <div className="flex flex-col">
                <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Palabras</span>
                <span className={clsx("text-xl font-black", pricing.wordCount > 0 ? "text-blue-600" : "text-slate-300")}>
                  {pricing.wordCount.toString().padStart(2, '0')}
                </span>
              </div>
              {pricing.specialCharCount > 0 && (
                <div className="flex flex-col">
                  <span className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Signos</span>
                  <span className="text-xl font-black text-orange-500">
                    {pricing.specialCharCount.toString().padStart(2, '0')}
                  </span>
                </div>
              )}
            </div>
            {loadingPrice && (
              <div className="flex items-center gap-2 text-[10px] font-black text-slate-400 uppercase animate-pulse">
                Sincronizando tarifa...
              </div>
            )}
          </div>
        </section>

        {/* BLOQUE 2: CONFIGURACIÓN DE PUBLICACIÓN */}
        <section className="bg-white p-8 rounded-[2.5rem] shadow-xl border border-slate-100 space-y-8">

          <div className="flex flex-col md:flex-row gap-8 justify-between">
            {/* Días */}
            <div className="flex items-center gap-6">
              <div className="p-3 bg-slate-900 rounded-2xl text-white">
                <Calendar size={20} />
              </div>
              <div>
                <h4 className="font-black uppercase text-xs text-slate-900">Duración</h4>
                <div className="flex items-center bg-slate-100 rounded-xl p-1 mt-2">
                  <button onClick={() => setDays(Math.max(1, days - 1))} className="w-10 py-2 font-black text-lg text-slate-400 hover:text-slate-900">-</button>
                  <input
                    type="number"
                    value={days}
                    onChange={(e) => setDays(parseInt(e.target.value) || 1)}
                    className="w-12 text-center bg-transparent border-none outline-none font-black text-lg text-blue-600"
                  />
                  <button onClick={() => setDays(days + 1)} className="w-10 py-2 font-black text-lg text-slate-400 hover:text-slate-900">+</button>
                </div>
              </div>
            </div>

            {/* Fecha de Inicio */}
            <div className="flex items-center gap-6">
              <div className="p-3 bg-blue-50 rounded-2xl text-blue-600">
                <Calendar size={20} />
              </div>
              <div>
                <h4 className="font-black uppercase text-xs text-slate-900">Fecha de Inicio</h4>
                <input
                  type="date"
                  value={startDate.toISOString().split('T')[0]}
                  min={new Date().toISOString().split('T')[0]}
                  onChange={(e) => setStartDate(new Date(e.target.value))}
                  className="mt-2 text-sm font-bold text-slate-700 bg-slate-100 rounded-xl px-4 py-2 outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>
          </div>

          <div className="h-px bg-slate-100 w-full"></div>

          <div className="flex flex-col md:flex-row gap-8 justify-between items-start">
            {/* Destacado */}
            <label className="flex items-center gap-4 cursor-pointer group">
              <div className={`w-14 h-8 rounded-full p-1 transition-colors ${isFeatured ? 'bg-amber-400' : 'bg-slate-200'}`}>
                <div className={`w-6 h-6 rounded-full bg-white shadow-sm transition-transform ${isFeatured ? 'translate-x-6' : ''}`} />
              </div>
              <div>
                <h4 className="font-black uppercase text-xs text-slate-900 group-hover:text-amber-500 transition-colors">Destacar Aviso</h4>
                <p className="text-[10px] text-slate-400 font-bold">Posición preferencial (+ $500/día)</p>
              </div>
              <input type="checkbox" className="hidden" checked={isFeatured} onChange={(e) => setIsFeatured(e.target.checked)} />
            </label>

            {/* Permitir Contacto */}
            <label className="flex items-center gap-4 cursor-pointer group">
              <div className={`w-14 h-8 rounded-full p-1 transition-colors ${allowContact ? 'bg-green-500' : 'bg-slate-200'}`}>
                <div className={`w-6 h-6 rounded-full bg-white shadow-sm transition-transform ${allowContact ? 'translate-x-6' : ''}`} />
              </div>
              <div>
                <h4 className="font-black uppercase text-xs text-slate-900 group-hover:text-green-600 transition-colors">Permitir Contacto</h4>
                <p className="text-[10px] text-slate-400 font-bold">Mostrar botón de WhatsApp/Email</p>
              </div>
              <input type="checkbox" className="hidden" checked={allowContact} onChange={(e) => setAllowContact(e.target.checked)} />
            </label>
          </div>

          <div className="bg-slate-50 p-6 rounded-2xl flex items-center gap-4">
            <span className="text-xs font-black uppercase text-slate-400">Cupón:</span>
            <input
              type="text"
              value={couponCode}
              onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
              placeholder="CÓDIGO"
              className="bg-transparent border-b-2 border-slate-200 focus:border-blue-500 outline-none font-mono font-bold text-slate-700 w-32 text-center uppercase"
            />
            {pricing.discount > 0 && <span className="text-xs font-bold text-green-600">¡Aplicado!</span>}
          </div>

        </section>

        {/* BLOQUE 3: PREVISUALIZACIÓN */}
        <section className="bg-[#fffef5] p-8 rounded-[2.5rem] border-2 border-yellow-100 shadow-inner relative overflow-hidden group">
          <div className="absolute top-0 right-0 p-8 opacity-5 group-hover:opacity-10 transition-opacity">
            <Eye size={120} />
          </div>

          <div className="flex items-center gap-3 mb-6 text-yellow-700 relative z-10">
            <Eye size={18} />
            <h3 className="font-black uppercase tracking-[0.2em] text-[10px]">Vista Previa Real</h3>
          </div>

          <div className="bg-white p-8 rounded-[1.8rem] border border-yellow-200 shadow-sm min-h-[10rem] relative z-10">
            {text ? (
              <p className="text-slate-800 text-lg font-medium leading-relaxed italic uppercase">
                {text}
              </p>
            ) : (
              <p className="text-slate-300 font-bold text-center py-10 uppercase tracking-widest text-xs">
                El texto aparecerá aquí...
              </p>
            )}
          </div>
        </section>

        {/* BLOQUE 4: COSTO FINAL */}
        <section className="bg-slate-900 rounded-[3rem] p-10 text-white shadow-2xl relative overflow-hidden">
          <div className="absolute top-0 right-0 w-64 h-64 bg-blue-600/10 rounded-full blur-[80px] -mr-32 -mt-32"></div>

          <div className="flex flex-col md:flex-row justify-between items-center gap-8 relative z-10">
            <div className="text-center md:text-left">
              <span className="text-[10px] font-black uppercase tracking-[0.3em] text-blue-400 mb-2 block">Total a Pagar</span>
              <div className="flex items-baseline justify-center md:justify-start gap-2">
                <span className="text-2xl font-black text-blue-500">$</span>
                <span className="text-6xl font-black tracking-tighter font-mono">
                  {pricing.totalPrice.toLocaleString('es-AR', { minimumFractionDigits: 2 })}
                </span>
              </div>
            </div>

            <div className="w-full md:w-64 space-y-3 bg-white/5 p-6 rounded-3xl border border-white/10 backdrop-blur-sm">
              <div className="flex justify-between text-[10px] font-black uppercase">
                <span className="text-slate-500">Tarifa base</span>
                <span className="text-white">${pricing.baseCost.toLocaleString()}</span>
              </div>
              {pricing.extraCost > 0 && (
                <div className="flex justify-between text-[10px] font-black uppercase text-orange-400">
                  <span>Recargo texto</span>
                  <span>+${pricing.extraCost.toLocaleString()}</span>
                </div>
              )}
              <div className="h-px bg-white/10 my-2"></div>
              <p className="text-[9px] text-slate-500 font-bold leading-tight italic">
                * {pricing.details || "Calculando tasas e impuestos..."}
              </p>
            </div>
          </div>
        </section>

        {/* BOTONES DE NAVEGACIÓN */}
        <div className="flex flex-col md:flex-row gap-4 pt-6">
          <button
            onClick={() => setStep(3)}
            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"
          >
            <ArrowLeft size={16} /> Volver
          </button>
          <button
            onClick={handleContinue}
            disabled={text.trim().length === 0 || loadingPrice}
            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"
          >
            Continuar a Fotos
            <ChevronRight size={18} className="group-hover:translate-x-1 transition-transform" />
          </button>
        </div>
      </div>
    </StepWrapper>
  );
}