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

interface AdminState {
  employees: EmployeeWithRate[] | null;
  employeesError: string | null;
  employeesBusy: boolean;

  stats: AdminStatsSummary | null;

  month: string; // "YYYY-MM", the period shown for the selected employee's detail
  selectedEmployeeId: number | null;
  employeeDetail: StatsSummary | null;
  detailLoading: boolean;

  loadEmployees: () => Promise<void>;
  addEmployee: (email: string) => Promise<void>;
  removeEmployee: (id: number) => Promise<void>;
  setRate: (id: number, hourlyRate: number) => Promise<void>;

  loadStats: () => Promise<void>;
  selectEmployee: (id: number) => Promise<void>;
  setMonth: (month: string) => Promise<void>;
  prevMonth: () => Promise<void>;
  nextMonth: () => Promise<void>;
}

const useAdminStore = create<AdminState>((set, get) => ({
  employees: null,
  employeesError: null,
  employeesBusy: false,

  stats: null,

  month: currentMonthKey(),
  selectedEmployeeId: null,
  employeeDetail: null,
  detailLoading: false,

  loadEmployees: async () => {
    try {
      const res = await api.get<{ employees: EmployeeWithRate[] }>('/admin/employees');
      set({ employees: res.employees, employeesError: null });
    } catch {
      set({ employeesError: 'Nepodařilo se načíst zaměstnance' });
    }
  },

  setRate: async (id, hourlyRate) => {
    set({ employeesBusy: true, employeesError: null });
    try {
      await api.post(`/admin/employees/${id}/rate`, { hourly_rate: hourlyRate });
      await get().loadEmployees();
    } catch (err) {
      set({ employeesError: err instanceof ApiError ? err.message : 'Uložení sazby se nezdařilo' });
    } finally {
      set({ employeesBusy: false });
    }
  },

  addEmployee: async (email) => {
    set({ employeesBusy: true, employeesError: null });
    try {
      await api.post('/admin/employees', { email });
      await get().loadEmployees();
    } catch (err) {
      set({ employeesError: err instanceof ApiError ? err.message : 'Přidání se nezdařilo' });
    } finally {
      set({ employeesBusy: false });
    }
  },

  removeEmployee: async (id) => {
    set({ employeesBusy: true, employeesError: null });
    try {
      await api.delete(`/admin/employees/${id}`);
      await get().loadEmployees();
    } catch (err) {
      set({ employeesError: err instanceof ApiError ? err.message : 'Odebrání se nezdařilo' });
    } finally {
      set({ employeesBusy: false });
    }
  },

  loadStats: async () => {
    const res = await api.get<AdminStatsSummary>(`/admin/stats?month=${get().month}`);
    set({ stats: res });
  },

  selectEmployee: async (id) => {
    set({ selectedEmployeeId: id, detailLoading: true });
    try {
      const res = await api.get<StatsSummary>(`/admin/stats/${id}?month=${get().month}`);
      set({ employeeDetail: res });
    } finally {
      set({ detailLoading: false });
    }
  },

  setMonth: async (month) => {
    set({ month });
    await get().loadStats();
    const id = get().selectedEmployeeId;
    if (id != null) await get().selectEmployee(id);
  },

  prevMonth: async () => {
    await get().setMonth(shiftMonthKey(get().month, -1));
  },

  nextMonth: async () => {
    await get().setMonth(shiftMonthKey(get().month, 1));
  },
}));

export default useAdminStore;
