import { useEffect, useState } from 'react';
import { wizardService } from '../../services/wizardService';
import { useWizardStore } from '../../store/wizardStore';
import type { Category } from '../../types'; // ID: type-import-fix
import { StepWrapper } from '../../components/StepWrapper';
import { ChevronRight } from 'lucide-react';

export default function CategoryParams() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [navStack, setNavStack] = useState<Category[]>([]); // For hierarchical navigation
  const setCategory = useWizardStore(state => state.setCategory);

  useEffect(() => {
    wizardService.getCategories().then(setCategories);
  }, []);

  // Filter categories dependent on current parent
  const currentParentId = navStack.length > 0 ? navStack[navStack.length - 1].id : null;
  const displayedCategories = categories.filter(c => c.parentId === currentParentId);

  const handleSelect = (category: Category) => {
    const hasChildren = categories.some(c => c.parentId === category.id);
    if (hasChildren) {
      setNavStack([...navStack, category]);
    } else {
      setCategory(category);
    }
  };

  const handleBack = () => {
    if (navStack.length > 0) {
      setNavStack(navStack.slice(0, -1));
    }
  };

  return (
    <StepWrapper>
      <h2 className="text-2xl font-bold mb-6 text-brand-900">¿Qué deseas publicar?</h2>

      {navStack.length > 0 && (
        <button
          onClick={handleBack}
          className="mb-4 text-sm text-brand-600 hover:text-brand-800 flex items-center gap-1"
        >
          &larr; Volver a {navStack.length > 1 ? navStack[navStack.length - 2].name : 'Inicio'}
        </button>
      )}

      <div className="grid gap-3">
        {displayedCategories.map(cat => (
          <button
            key={cat.id}
            onClick={() => handleSelect(cat)}
            className="group flex items-center justify-between p-4 bg-white border border-slate-200 rounded-lg shadow-sm hover:border-brand-500 hover:ring-1 hover:ring-brand-500 transition-all text-left"
          >
            <span className="font-medium text-slate-700 group-hover:text-brand-700">{cat.name}</span>
            <ChevronRight className="text-slate-400 group-hover:text-brand-500" />
          </button>
        ))}
      </div>
    </StepWrapper>
  );
}
