import { useEffect, useState } from 'react';
import { wizardService } from '../../services/wizardService';
import { useWizardStore } from '../../store/wizardStore';
import type { AttributeDefinition } from '../../types';
import { StepWrapper } from '../../components/StepWrapper';
import { ChevronRight, Info, Tag, PenTool, DollarSign } from 'lucide-react';

export default function AttributeForm() {
  const { selectedCategory, selectedOperation, attributes, setAttribute, setStep } = useWizardStore();
  const [definitions, setDefinitions] = useState<AttributeDefinition[]>([]);

  useEffect(() => {
    // CAMBIO: Verificamos específicamente que exista el ID para evitar el GET /undefined
    if (selectedCategory?.id) {
      wizardService.getAttributes(selectedCategory.id)
        .then(setDefinitions)
        .catch(err => console.error("Error al obtener atributos:", err));
    }
  }, [selectedCategory?.id]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setStep(4);
  };

  return (
    <StepWrapper>
      {/* Breadcrumbs */}
      <div className="flex items-center gap-3 mb-8 px-1">
        <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-slate-400">
          <button onClick={() => setStep(1)} className="hover:text-blue-600 transition-colors">
            {selectedCategory?.name}
          </button>
          <ChevronRight size={10} className="opacity-30" />
          <button onClick={() => setStep(2)} className="hover:text-blue-600 transition-colors">
            {selectedOperation?.name}
          </button>
        </div>
      </div>

      <div className="mb-10">
        <h2 className="text-4xl font-black text-slate-900 tracking-tighter uppercase leading-none">
          Características <br />
          <span className="text-blue-600">del Anuncio</span>
        </h2>
        <p className="text-slate-400 text-sm mt-3 font-medium">Completa los datos técnicos para mejorar la visibilidad.</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-8">
        {/* GRUPO: INFORMACIÓN BÁSICA */}
        <div className="space-y-6 bg-white p-8 rounded-[2.5rem] border border-slate-100 shadow-sm">
          <div className="flex items-center gap-2 text-blue-600 mb-2">
            <PenTool size={16} />
            <span className="text-[10px] font-black uppercase tracking-[0.2em]">Información General</span>
          </div>

          <div className="space-y-2">
            <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1">Título del Aviso</label>
            <input
              type="text"
              required
              className="w-full p-4 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none focus:border-blue-500 focus:bg-white transition-all font-bold text-slate-700 text-sm"
              onChange={(e) => setAttribute('title', e.target.value)}
              value={attributes['title'] || ''}
            />
          </div>

          <div className="space-y-2">
            <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1">Precio de Venta</label>
            <div className="relative flex items-center">
              {/* Icono de moneda separado del texto */}
              <div className="absolute left-4 text-slate-400 font-black text-lg pointer-events-none">
                <DollarSign size={18} />
              </div>
              <input
                type="number"
                required
                /* Aumentamos pl-12 para evitar superposición */
                className="w-full p-4 pl-12 bg-slate-50 border-2 border-slate-100 rounded-2xl outline-none focus:border-blue-500 focus:bg-white transition-all font-mono font-black text-slate-800 text-lg"
                onChange={(e) => setAttribute('price', e.target.value)}
                value={attributes['price'] || ''}
              />
            </div>
          </div>
        </div>

        {/* GRUPO: ESPECIFICACIONES TÉCNICAS */}
        {definitions.length > 0 && (
          <div className="space-y-6 bg-slate-50/50 p-8 rounded-[2.5rem] border-2 border-slate-100">
            <div className="flex items-center gap-2 text-slate-500 mb-2">
              <Tag size={16} />
              <span className="text-[10px] font-black uppercase tracking-[0.2em]">Ficha Técnica</span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {definitions.map(def => (
                <div key={def.id} className="space-y-2">
                  <label className="text-[10px] font-black text-slate-500 uppercase tracking-widest ml-1">
                    {def.name} {def.required && <span className="text-rose-500">*</span>}
                  </label>

                  <input
                    type={def.dataType === 'number' ? 'number' : 'text'}
                    required={def.required}
                    placeholder={`Ingrese ${def.name.toLowerCase()}...`}
                    className="w-full p-4 bg-white border-2 border-slate-100 rounded-2xl outline-none focus:border-blue-500 transition-all font-bold text-slate-700 text-sm placeholder:text-slate-200 shadow-sm"
                    value={attributes[def.name.toLowerCase()] || ''}
                    onChange={(e) => setAttribute(def.name.toLowerCase(), e.target.value)}
                  />
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="p-6 bg-blue-50 rounded-3xl flex gap-4 border border-blue-100 items-start">
          <Info className="text-blue-500 shrink-0" size={20} />
          <p className="text-[10px] text-blue-700 font-bold leading-relaxed uppercase opacity-80">
            Los datos cargados aquí sirven para filtrar las búsquedas en el portal digital.
          </p>
        </div>

        {/* BOTÓN CON ALTO CONTRASTE */}
        <button
          type="submit"
          className="w-full bg-slate-950 hover:bg-black text-white font-black uppercase text-xs tracking-[0.2em] py-6 rounded-[2rem] shadow-2xl shadow-slate-300 transition-all mt-6 active:scale-[0.98] flex items-center justify-center gap-3 group"
        >
          Continuar al Editor de Texto
          <ChevronRight size={18} className="group-hover:translate-x-1 transition-transform" />
        </button>
      </form>
    </StepWrapper>
  );
}