import { create } from 'zustand';
import { api } from '../api/client';
import type { TrainingSet, CreateSetRequest, UpdateSetRequest } from '../types';
import { useToastStore } from './toastStore';

interface SetState {
  sets: TrainingSet[];
  loading: boolean;
  error: string | null;
  fetchSets: () => Promise<void>;
  createSet: (data: CreateSetRequest) => Promise<TrainingSet | null>;
  updateSet: (id: number, data: UpdateSetRequest) => Promise<TrainingSet | null>;
  deleteSet: (id: number) => Promise<boolean>;
}

export const useSetStore = create<SetState>((set, get) => ({
  sets: [],
  loading: false,
  error: null,

  fetchSets: async () => {
    set({ loading: true, error: null });
    try {
      const sets = await api.sets.list();
      set({ sets: sets || [], loading: false });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Laden';
      set({ error: message, loading: false });
    }
  },

  createSet: async (data) => {
    try {
      const newSet = await api.sets.create(data);
      useToastStore.getState().addToast('success', 'Set erstellt');
      await get().fetchSets();
      return newSet;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Erstellen';
      useToastStore.getState().addToast('error', message);
      return null;
    }
  },

  updateSet: async (id, data) => {
    try {
      const updated = await api.sets.update(id, data);
      useToastStore.getState().addToast('success', 'Set aktualisiert');
      await get().fetchSets();
      return updated;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Aktualisieren';
      useToastStore.getState().addToast('error', message);
      return null;
    }
  },

  deleteSet: async (id) => {
    try {
      await api.sets.delete(id);
      useToastStore.getState().addToast('success', 'Set gelöscht');
      await get().fetchSets();
      return true;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Löschen';
      useToastStore.getState().addToast('error', message);
      return false;
    }
  },
}));
