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

export interface SlotFormData {
  date: string;
  start_time: string;
  end_time: string;
  capacity: number;
  note?: string;
}

interface AdminShiftState {
  period: string;
  slots: AdminShiftSlot[] | null;
  busy: boolean;
  error: string | null;

  load: () => Promise<void>;
  setPeriod: (period: string) => Promise<void>;
  prevPeriod: () => Promise<void>;
  nextPeriod: () => Promise<void>;
  createSlot: (data: SlotFormData) => Promise<void>;
  updateSlot: (slotId: number, data: SlotFormData) => Promise<void>;
  assignEmployee: (slotId: number, employeeId: number) => Promise<void>;
  removeEmployee: (slotId: number, employeeId: number) => Promise<void>;
}

const useAdminShiftStore = create<AdminShiftState>((set, get) => ({
  period: currentMonthKey(),
  slots: null,
  busy: false,
  error: null,

  load: async () => {
    try {
      const res = await api.get<{ slots: AdminShiftSlot[] }>(`/admin/shifts?period=${get().period}`);
      set({ slots: res.slots, error: null });
    } catch {
      set({ error: 'Nepodařilo se načíst plán směn' });
    }
  },

  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));
  },

  createSlot: async (data) => {
    set({ busy: true, error: null });
    try {
      await api.post('/admin/shifts', data);
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Vytvoření se nezdařilo' });
    } finally {
      set({ busy: false });
    }
  },

  updateSlot: async (slotId, data) => {
    set({ busy: true, error: null });
    try {
      await api.patch(`/admin/shifts/${slotId}`, data);
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Úprava se nezdařila' });
    } finally {
      set({ busy: false });
    }
  },

  assignEmployee: async (slotId, employeeId) => {
    set({ busy: true, error: null });
    try {
      await api.post(`/admin/shifts/${slotId}/assign`, { employeeId });
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Přiřazení se nezdařilo' });
    } finally {
      set({ busy: false });
    }
  },

  removeEmployee: async (slotId, employeeId) => {
    set({ busy: true, error: null });
    try {
      await api.delete(`/admin/shifts/${slotId}/assign/${employeeId}`);
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Odebrání se nezdařilo' });
    } finally {
      set({ busy: false });
    }
  },
}));

export default useAdminShiftStore;
