import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useWizardStore } from '../store/wizardStore';
import CategorySelection from './Steps/CategorySelection';
import OperationSelection from './Steps/OperationSelection';
import AttributeForm from './Steps/AttributeForm';
import TextEditorStep from './Steps/TextEditorStep';
import PhotoUploadStep from './Steps/PhotoUploadStep';
import SummaryStep from './Steps/SummaryStep';
import { wizardService } from '../services/wizardService';
import type { AttributeDefinition } from '../types';
import SEO from '../components/SEO';
import api from '../services/api';
import { User as UserIcon } from 'lucide-react';

export default function PublishPage() {
  const { step, selectedCategory } = useWizardStore();
  const [definitions, setDefinitions] = useState<AttributeDefinition[]>([]);
  const [profileComplete, setProfileComplete] = useState<boolean | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    api.get('/profile').then(res => {
      const data = res.data;
      const isComplete = !!(data.billingName && data.billingAddress && data.billingTaxId && data.billingTaxType);
      setProfileComplete(isComplete);
    }).catch(() => setProfileComplete(false));
  }, []);

  useEffect(() => {
    if (selectedCategory?.id) {
      wizardService.getAttributes(selectedCategory.id)
        .then(setDefinitions)
        .catch(err => console.error("Error en PublishPage:", err));
    }
  }, [selectedCategory?.id]);

  if (profileComplete === null) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  if (profileComplete === false) {
    return (
      <div className="min-h-[70vh] flex flex-col items-center justify-center p-10 text-center animate-in fade-in zoom-in duration-500">
        <div className="w-24 h-24 bg-amber-50 text-amber-500 rounded-[2.5rem] flex items-center justify-center mb-8 shadow-xl shadow-amber-100 border border-amber-100">
          <UserIcon size={48} />
        </div>
        <h2 className="text-3xl font-black text-slate-900 uppercase tracking-tighter mb-4">Perfil Incompleto</h2>
        <p className="text-slate-500 max-w-sm mb-10 font-medium leading-relaxed">
          Para poder publicar un aviso, primero debes completar tus datos de facturación. Esto es obligatorio para la emisión legal de comprobantes.
        </p>
        <button
          onClick={() => navigate('/profile?tab=settings')}
          className="bg-slate-900 text-white px-12 py-5 rounded-[2rem] font-black uppercase text-xs tracking-widest shadow-2xl shadow-slate-200 hover:bg-blue-600 transition-all active:scale-95"
        >
          Completar mis datos ahora
        </button>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50 text-slate-900 font-sans pb-20">
      <SEO
        title="Publicar Aviso"
        description="Publica tu aviso clasificado en simples pasos."
      />

      {/* Header del Wizard interno */}
      <div className="bg-white border-b border-slate-200 sticky top-[80px] z-30 shadow-sm">
        <div className="max-w-3xl mx-auto px-4 h-14 flex items-center justify-between">
          <span className="text-[10px] font-black uppercase tracking-widest text-slate-400">
            Paso {step} de 6
          </span>
          <div className="flex gap-1">
            {[1, 2, 3, 4, 5, 6].map((i) => (
              <div
                key={i}
                className={`w-8 h-1.5 rounded-full transition-colors ${i <= step ? 'bg-blue-600' : 'bg-slate-100'}`}
              />
            ))}
          </div>
        </div>
      </div>

      <main className="max-w-3xl mx-auto p-6 mt-8 bg-white rounded-[2.5rem] shadow-xl shadow-slate-200/50 border border-slate-100">
        {step === 1 && <CategorySelection />}
        {step === 2 && <OperationSelection />}
        {step === 3 && <AttributeForm />}
        {step === 4 && <TextEditorStep />}
        {step === 5 && <PhotoUploadStep />}
        {step === 6 && <SummaryStep definitions={definitions} />}
      </main>
    </div>
  );
}