import { create } from 'zustand'
import { hrApi } from '@/lib/api'

export interface Employee {
  id: string
  name: string
  email: string
  phone: string
  department: string
  position: string
  start_date: string
  status: string
}

export interface Leave {
  id: string
  employee_id: string
  type: string
  start_date: string
  end_date: string
  status: string
}

interface HRState {
  employees: Employee[]
  leaves: Leave[]
  loading: boolean
  error: string | null
  fetchEmployees: () => Promise<void>
  fetchLeaves: () => Promise<void>
  createEmployee: (data: Partial<Employee>) => Promise<void>
  createLeave: (data: Partial<Leave>) => Promise<void>
}

export const useHRStore = create<HRState>((set, get) => ({
  employees: [],
  leaves: [],
  loading: false,
  error: null,

  fetchEmployees: async () => {
    set({ loading: true, error: null })
    try {
      const data = await hrApi.employees()
      set({ employees: (data.employees || []) as Employee[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch employees', loading: false })
    }
  },

  fetchLeaves: async () => {
    set({ loading: true, error: null })
    try {
      const data = await hrApi.leaves()
      set({ leaves: (data.leaves || []) as Leave[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch leaves', loading: false })
    }
  },

  createEmployee: async (data) => {
    set({ loading: true, error: null })
    try {
      await hrApi.createEmployee(data)
      await get().fetchEmployees()
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to create employee', loading: false })
    }
  },

  createLeave: async (data) => {
    set({ loading: true, error: null })
    try {
      await hrApi.createLeave(data)
      await get().fetchLeaves()
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to create leave', loading: false })
    }
  },
}))
