import { create } from 'zustand';
import { api, ApiError } from '../api/client';
import type { AvailableShiftSlot, MyShiftSlot } from '../api/types';
import { currentMonthKey, shiftMonthKey } from '../lib/month';

interface ShiftPlanningState {
  period: string;
  available: AvailableShiftSlot[] | null;
  mine: MyShiftSlot[] | null;
  busy: boolean;
  error: string | null;

  load: () => Promise<void>;
  setPeriod: (period: string) => Promise<void>;
  prevPeriod: () => Promise<void>;
  nextPeriod: () => Promise<void>;
  signup: (slotId: number) => Promise<void>;
  cancel: (slotId: number) => Promise<void>;
}

const useShiftPlanningStore = create<ShiftPlanningState>((set, get) => ({
  period: currentMonthKey(),
  available: null,
  mine: null,
  busy: false,
  error: null,

  load: async () => {
    try {
      const period = get().period;
      const [availableRes, mineRes] = await Promise.all([
        api.get<{ slots: AvailableShiftSlot[] }>(`/shifts/available?period=${period}`),
        api.get<{ slots: MyShiftSlot[] }>(`/shifts/mine?period=${period}`),
      ]);
      set({ available: availableRes.slots, mine: mineRes.slots, error: null });
    } catch {
      set({ error: 'Nepodařilo se načíst směny' });
    }
  },

  setPeriod: async (period) => {
    set({ period });
    await get().load();
  },

  prevPeriod: async () => {
    await get().setPeriod(shiftMonthKey(get().period, -1));
  },

  nextPeriod: async () => {
    await get().setPeriod(shiftMonthKey(get().period, 1));
  },

  signup: async (slotId) => {
    set({ busy: true, error: null });
    try {
      await api.post(`/shifts/${slotId}/signup`);
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Přihlášení se nezdařilo' });
    } finally {
      set({ busy: false });
    }
  },

  cancel: async (slotId) => {
    set({ busy: true, error: null });
    try {
      await api.delete(`/shifts/${slotId}/signup`);
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Zrušení se nezdařilo' });
    } finally {
      set({ busy: false });
    }
  },
}));

export default useShiftPlanningStore;
