import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { Category, Operation, Listing } from '../types';

interface WizardState {
  step: number;
  selectedCategory: Category | null;
  selectedOperation: Operation | null;
  attributes: Record<string, string>;
  photos: File[];
  setStep: (step: number) => void;
  setCategory: (category: Category) => void;
  setOperation: (operation: Operation) => void;
  setAttribute: (key: string, value: string) => void;
  addPhoto: (file: File) => void;
  removePhoto: (index: number) => void;
  setRepublishData: (listing: Listing) => void;
  reset: () => void;
  existingImages: any[];
  removeExistingImage: (index: number) => void;
}

export const useWizardStore = create<WizardState>()(
  persist(
    (set) => ({
      step: 1,
      selectedCategory: null,
      selectedOperation: null,
      attributes: {},
      photos: [],
      existingImages: [],

      setStep: (step) => set({ step }),

      setCategory: (category) => set({ selectedCategory: category, step: 2 }),

      setOperation: (operation) => set({ selectedOperation: operation, step: 3 }),

      setAttribute: (key, value) => set((state) => ({
        attributes: { ...state.attributes, [key]: value }
      })),

      addPhoto: (file) => set((state) => ({ photos: [...state.photos, file] })),

      removePhoto: (index) => set((state) => ({ photos: state.photos.filter((_, i) => i !== index) })),

      // REPUBLICACIÓN
      setRepublishData: (data: any) => {
        const listing = data.listing || data.Listing || data;

        // Extraemos el ID con soporte para ambos casos
        const catId = listing.categoryId ?? listing.CategoryId;

        if (!catId) {
          console.error("Error crítico: No se encontró CategoryId en:", data);
          return;
        }

        // 1. Mapeamos campos estáticos (siempre en minúsculas para el form)
        const mappedAttributes: Record<string, string> = {
          title: listing.title || listing.Title || '',
          description: listing.description || listing.Description || '',
          price: (listing.price || listing.Price || '0').toString(),
        };

        // 2. Mapeamos atributos dinámicos
        const attributesArray = data.attributes || data.Attributes || [];
        if (Array.isArray(attributesArray)) {
          attributesArray.forEach((attr: any) => {
            // Normalizamos la clave del atributo a minúsculas
            const rawKey = attr.attributeName || attr.AttributeName;
            if (rawKey) {
              const key = rawKey.toLowerCase();
              mappedAttributes[key] = (attr.value || attr.Value || '').toString();
            }
          });
        }

        const imagesArray = data.images || data.Images || [];

        set({
          step: 3,
          selectedCategory: {
            id: catId,
            name: listing.categoryName || listing.CategoryName || 'Rubro'
          } as any,
          selectedOperation: {
            id: listing.operationId || listing.OperationId,
            name: 'Venta'
          } as any,
          attributes: mappedAttributes,
          existingImages: imagesArray,
          photos: []
        });
      },

      removeExistingImage: (index: number) => set((state) => ({
        existingImages: state.existingImages.filter((_, i) => i !== index)
      })),

      reset: () => {
        localStorage.removeItem('wizard-storage');
        set({ step: 1, selectedCategory: null, selectedOperation: null, attributes: {}, photos: [], existingImages: [] });
      },
    }),
    {
      name: 'wizard-storage',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        step: state.step,
        selectedCategory: state.selectedCategory,
        selectedOperation: state.selectedOperation,
        attributes: state.attributes,
      }),
    },
  )
);