import { createSlice, createAsyncThunk, type PayloadAction } from "@reduxjs/toolkit"

// Define a type for the department
export interface Department {
  id: number
  name: string
  teamMembersCount: number
  description: string
}

// Define the state type
interface DepartmentsState {
  items: Department[]
  status: "idle" | "loading" | "succeeded" | "failed"
  error: string | null
  selectedDepartment: Department | null
  filters: {
    search: string
  }
}

// Initial state
const initialState: DepartmentsState = {
  items: [],
  status: "idle",
  error: null,
  selectedDepartment: null,
  filters: {
    search: "",
  },
}

// Sample data for initial development
const sampleDepartments: Department[] = [
  {
    id: 1,
    name: "Operations",
    teamMembersCount: 32,
    description: "Manages day-to-day operational activities and logistics coordination.",
  },
  {
    id: 2,
    name: "Administration",
    teamMembersCount: 15,
    description: "Handles administrative tasks, office management, and internal processes.",
  },
  // More sample data can be added here
]

// Async thunks for API calls
export const fetchDepartments = createAsyncThunk("departments/fetchDepartments", async (_, { rejectWithValue }) => {
  try {
    // In a real app, this would be an API call
    await new Promise((resolve) => setTimeout(resolve, 1000))
    return sampleDepartments
  } catch (error) {
    return rejectWithValue("Failed to fetch departments")
  }
})

// Create the slice
const departmentsSlice = createSlice({
  name: "departments",
  initialState,
  reducers: {
    setSelectedDepartment: (state, action: PayloadAction<Department | null>) => {
      state.selectedDepartment = action.payload
    },
    updateFilters: (state, action: PayloadAction<Partial<DepartmentsState["filters"]>>) => {
      state.filters = { ...state.filters, ...action.payload }
    },
    resetFilters: (state) => {
      state.filters = initialState.filters
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchDepartments.pending, (state) => {
        state.status = "loading"
      })
      .addCase(fetchDepartments.fulfilled, (state, action) => {
        state.status = "succeeded"
        state.items = action.payload
      })
      .addCase(fetchDepartments.rejected, (state, action) => {
        state.status = "failed"
        state.error = action.payload as string
      })
  },
})

export const { setSelectedDepartment, updateFilters, resetFilters } = departmentsSlice.actions

export default departmentsSlice.reducer

