import { create } from 'zustand';
import { apiService } from '@/services/api';
import type { LibraryItem, PaginatedResponse, ApiError } from '@/types';

interface LibraryState {
  items: LibraryItem[];
  favorites: LibraryItem[];
  isLoading: boolean;
  error: ApiError | null;
  pagination: {
    page: number;
    limit: number;
    total: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  filters: {
    type?: string;
    search?: string;
  };
}

interface LibraryActions {
  fetchItems: (params?: {
    page?: number;
    limit?: number;
    type?: string;
    search?: string;
  }) => Promise<void>;
  fetchFavorites: () => Promise<void>;
  uploadFile: (
    file: File,
    metadata: { title: string; description?: string }
  ) => Promise<void>;
  toggleFavorite: (itemId: string) => Promise<void>;
  deleteItem: (itemId: string) => Promise<void>;
  setFilters: (filters: { type?: string; search?: string }) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: ApiError | null) => void;
  clearItems: () => void;
}

export const useLibraryStore = create<LibraryState & LibraryActions>(
  (set, get) => ({
    // État initial
    items: [],
    favorites: [],
    isLoading: false,
    error: null,
    pagination: {
      page: 1,
      limit: 20,
      total: 0,
      hasNext: false,
      hasPrev: false,
    },
    filters: {},

    // Actions
    fetchItems: async (params = {}) => {
      set({ isLoading: true, error: null });
      try {
        const {
          page = 1,
          limit = 20,
          type,
        } = { ...get().pagination, ...get().filters, ...params };

        const response: PaginatedResponse<LibraryItem> =
          await apiService.getLibraryItems({
            page,
            limit,
            type,
          });

        set({
          items: response.data,
          pagination: {
            page: response.page,
            limit: response.limit,
            total: response.total,
            hasNext: response.has_next,
            hasPrev: response.has_prev,
          },
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        set({
          error: error as ApiError,
          isLoading: false,
        });
      }
    },

    fetchFavorites: async () => {
      set({ isLoading: true, error: null });
      try {
        const response: PaginatedResponse<LibraryItem> =
          await apiService.getLibraryItems({
            page: 1,
            limit: 100,
            type: 'favorites',
          });

        set({
          favorites: response.data,
          isLoading: false,
          error: null,
        });
      } catch (error: any) {
        set({
          error: error as ApiError,
          isLoading: false,
        });
      }
    },

    uploadFile: async (file, metadata) => {
      set({ isLoading: true, error: null });
      try {
        const newItem = await apiService.uploadFile(file, metadata);

        set(state => ({
          items: [newItem, ...state.items],
          isLoading: false,
          error: null,
        }));
      } catch (error: any) {
        set({
          error: error as ApiError,
          isLoading: false,
        });
        throw error;
      }
    },

    toggleFavorite: async itemId => {
      try {
        const updatedItem = await apiService.toggleFavorite(itemId);

        set(state => ({
          items: state.items.map(item =>
            item.id === itemId
              ? { ...item, is_favorite: updatedItem.is_favorite }
              : item
          ),
          favorites: updatedItem.is_favorite
            ? [...state.favorites, updatedItem]
            : state.favorites.filter(item => item.id !== itemId),
        }));
      } catch (error: any) {
        set({ error: error as ApiError });
        throw error;
      }
    },

    deleteItem: async itemId => {
      try {
        // Appel API pour supprimer l'élément
        // await apiService.deleteItem(itemId)

        set(state => ({
          items: state.items.filter(item => item.id !== itemId),
          favorites: state.favorites.filter(item => item.id !== itemId),
        }));
      } catch (error: any) {
        set({ error: error as ApiError });
        throw error;
      }
    },

    setFilters: filters => {
      set({ filters });
      // Recharger les éléments avec les nouveaux filtres
      get().fetchItems({ page: 1 });
    },

    setLoading: isLoading => set({ isLoading }),

    setError: error => set({ error }),

    clearItems: () =>
      set({
        items: [],
        favorites: [],
        pagination: {
          page: 1,
          limit: 20,
          total: 0,
          hasNext: false,
          hasPrev: false,
        },
      }),
  })
);
