import { create } from 'zustand';
import { api } from './auth';

interface HRStore {
  roles: any[];
  grades: any[];
  records: any[];
  leaveRequests: any[];
  leaveTypes: any[];
  attendance: any[];

  fetchRoles: () => Promise<void>;
  fetchGrades: () => Promise<void>;
  fetchRecords: () => Promise<void>;
  fetchLeaveTypes: () => Promise<void>;
  fetchLeaveRequests: () => Promise<void>;
  fetchAttendance: (date?: string) => Promise<void>;

  createRole: (data: any) => Promise<void>;
  createGrade: (data: any) => Promise<void>;
  createRecord: (data: any) => Promise<void>;
  createLeaveRequest: (data: any) => Promise<void>;
  updateLeaveStatus: (uid: string, data: any) => Promise<void>;
  markAttendance: (data: any) => Promise<void>;
}

export const useHRStore = create<HRStore>((set, get) => ({
  roles: [],
  grades: [],
  records: [],
  leaveRequests: [],
  leaveTypes: [],
  attendance: [],

  fetchRoles: async () => {
    const response = await api.get('/api/hr/roles');
    set({ roles: response.data });
  },

  fetchGrades: async () => {
    const response = await api.get('/api/hr/salary-grades');
    set({ grades: response.data });
  },

  fetchRecords: async () => {
    const response = await api.get('/api/hr/records');
    set({ records: response.data });
  },

  fetchLeaveTypes: async () => {
    const response = await api.get('/api/hr/leave-types');
    set({ leaveTypes: response.data });
  },

  fetchLeaveRequests: async () => {
    const response = await api.get('/api/hr/leave-requests');
    set({ leaveRequests: response.data });
  },

  fetchAttendance: async (date) => {
    const response = await api.get(`/api/hr/attendance${date ? `?date=${date}` : ''}`);
    set({ attendance: response.data });
  },

  createRole: async (data: any) => {
    await api.post('/api/hr/roles', data);
    get().fetchRoles();
  },

  createGrade: async (data: any) => {
    await api.post('/api/hr/salary-grades', data);
    get().fetchGrades();
  },

  createRecord: async (data: any) => {
    await api.post('/api/hr/records', data);
    get().fetchRecords();
  },

  createLeaveRequest: async (data: any) => {
    await api.post('/api/hr/leave-requests', data);
    get().fetchLeaveRequests();
  },

  updateLeaveStatus: async (uid: string, data: any) => {
    await api.put(`/api/hr/leave-requests/${uid}/status`, data);
    get().fetchLeaveRequests();
  },

  markAttendance: async (data: any) => {
    await api.post('/api/hr/attendance', data);
    const today = new Date().toISOString().split('T')[0];
    get().fetchAttendance(today);
  },
}));
