import { create } from 'zustand';
import { api } from '../api/client';
import type { Exercise, MuscleGroup, CreateExerciseRequest } from '../types';
import { useToastStore } from './toastStore';

interface ExerciseFilter {
  muscleGroup: MuscleGroup | '';
  query: string;
}

interface ExerciseState {
  exercises: Exercise[];
  loading: boolean;
  error: string | null;
  filter: ExerciseFilter;
  fetchExercises: () => Promise<void>;
  createExercise: (data: CreateExerciseRequest) => Promise<Exercise | null>;
  updateExercise: (id: number, data: CreateExerciseRequest) => Promise<Exercise | null>;
  deleteExercise: (id: number) => Promise<boolean>;
  setFilter: (filter: Partial<ExerciseFilter>) => void;
}

export const useExerciseStore = create<ExerciseState>((set, get) => ({
  exercises: [],
  loading: false,
  error: null,
  filter: { muscleGroup: '', query: '' },

  fetchExercises: async () => {
    set({ loading: true, error: null });
    try {
      const { muscleGroup, query } = get().filter;
      const exercises = await api.exercises.list(muscleGroup || undefined, query || undefined);
      set({ exercises: exercises || [], loading: false });
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Laden';
      set({ error: message, loading: false });
    }
  },

  createExercise: async (data) => {
    try {
      const exercise = await api.exercises.create(data);
      useToastStore.getState().addToast('success', 'Übung erstellt');
      await get().fetchExercises();
      return exercise;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Erstellen';
      useToastStore.getState().addToast('error', message);
      return null;
    }
  },

  updateExercise: async (id, data) => {
    try {
      const exercise = await api.exercises.update(id, data);
      useToastStore.getState().addToast('success', 'Übung aktualisiert');
      await get().fetchExercises();
      return exercise;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Fehler beim Aktualisieren';
      useToastStore.getState().addToast('error', message);
      return null;
    }
  },

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

  setFilter: (filter) => {
    set((state) => ({
      filter: { ...state.filter, ...filter },
    }));
  },
}));
