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

// Define a type for the vehicle status
export interface VehicleStatus {
  id: number
  name: string
  description: string
  color?: string // Optional color code for visual representation
}

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

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

// Sample data for initial development
const sampleVehicleStatuses: VehicleStatus[] = [
  {
    id: 1,
    name: "Operational",
    description: "Vehicle is fully functional and available for service",
    color: "#22c55e", // green
  },
  {
    id: 2,
    name: "In Service",
    description: "Vehicle is currently assigned and in use",
    color: "#3b82f6", // blue
  },
  {
    id: 3,
    name: "Non-Functional",
    description: "Vehicle is not operational due to mechanical issues",
    color: "#ef4444", // red
  },
  {
    id: 4,
    name: "Under Maintenance",
    description: "Vehicle is undergoing scheduled maintenance",
    color: "#f59e0b", // amber
  },
  {
    id: 5,
    name: "Reserved",
    description: "Vehicle is reserved for future assignment",
    color: "#8b5cf6", // purple
  },
  {
    id: 6,
    name: "Available",
    description: "Vehicle is available for assignment",
    color: "#10b981", // emerald
  },
  {
    id: 7,
    name: "Out of Service",
    description: "Vehicle is temporarily out of service",
    color: "#64748b", // slate
  }
]

// Define the payload type for adding a new vehicle status
export interface AddVehicleStatusPayload {
  name: string
  description: string
  color?: string
}

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

export const addVehicleStatus = createAsyncThunk(
  "vehicleStatuses/addVehicleStatus",
  async (payload: AddVehicleStatusPayload, { rejectWithValue }) => {
    try {
      // In a real app, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000))

      // Generate a new ID (in a real app, the server would do this)
      return {
        id: Date.now(),
        name: payload.name,
        description: payload.description,
        color: payload.color,
      }
    } catch (error) {
      return rejectWithValue("Failed to add vehicle status")
    }
  },
)

export const deleteVehicleStatus = createAsyncThunk(
  "vehicleStatuses/deleteVehicleStatus",
  async (id: number, { rejectWithValue }) => {
    try {
      // In a real app, this would be an API call
      await new Promise((resolve) => setTimeout(resolve, 1000))
      return id
    } catch (error) {
      return rejectWithValue("Failed to delete vehicle status")
    }
  },
)

// Create the slice
const vehicleStatusesSlice = createSlice({
  name: "vehicleStatuses",
  initialState,
  reducers: {
    updateFilters: (state, action: PayloadAction<Partial<VehicleStatusesState["filters"]>>) => {
      state.filters = { ...state.filters, ...action.payload }
    },
    resetFilters: (state) => {
      state.filters = initialState.filters
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchVehicleStatuses.pending, (state) => {
        state.status = "loading"
      })
      .addCase(fetchVehicleStatuses.fulfilled, (state, action) => {
        state.status = "succeeded"
        state.items = action.payload
      })
      .addCase(fetchVehicleStatuses.rejected, (state, action) => {
        state.status = "failed"
        state.error = action.payload as string
      })
      .addCase(addVehicleStatus.fulfilled, (state, action) => {
        state.items.push(action.payload)
      })
      .addCase(deleteVehicleStatus.fulfilled, (state, action) => {
        state.items = state.items.filter((item) => item.id !== action.payload)
      })
  },
})

export const { updateFilters, resetFilters } = vehicleStatusesSlice.actions

export default vehicleStatusesSlice.reducer

