// src/store/userSlice.ts

import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import api from "../services/axiosClient";
import { BASE_URL } from "@/constants/config";

interface Vehicle {
  vehicle_id: number;
  model: string;
  chasis_number: string;
}

interface UserData {
  user_id: number;
  name: string;
  mobile: string;
  email: string | null;
  profile_url: string | null;
  vehicles: Vehicle[];
  batteries: Battery[];
}

interface Battery {
  battery_id: string;
  device_id: string;
  warranty_status: boolean;
  battery_model: string;
  bms_id: string;
  warranty_start_date: string;
  warranty_end_date: string;
  vim_id: string;
  serial_no: string;
  charger_uid: string;
}

interface UserState {
  data: UserData | null;
  loading: boolean;
  error: string | null;
}

const initialState: UserState = {
  data: null,
  loading: false,
  error: null,
};

// 🔁 Thunk to get user details
export const getUserDetails = createAsyncThunk<UserData>(
  "user/getUserDetails",
  async (_, { rejectWithValue }) => {
    try {
      console.log("Fetching user details from API...");
      console.log("BASE_URL", BASE_URL);
      const response = await api.get(`${BASE_URL}/api/v1/get-user-details`);
      if (response.data.success) {
        console.log("User details fetched successfully:", response.data.data);
        return response.data.data;
      } else {
        console.error("Failed to fetch user data:", response.data.message);
        return rejectWithValue("Failed to fetch user data");
      }
    } catch (error: any) {
      const message =
        error.response?.data?.message ||
        error.message ||
        "Something went wrong";
      console.log("Error fetching user details:", message);
      return rejectWithValue(message);
    }
  }
);

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    clearUser: (state) => {
      state.data = null;
      state.error = null;
      state.loading = false;
    },
    setUserData: (state, action: PayloadAction<Partial<UserData>>) => {
      if (state.data) {
        state.data = {
          ...state.data,
          ...action.payload,
        };
      } else {
        console.warn("Cannot update user data, user data is not loaded");
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getUserDetails.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(
        getUserDetails.fulfilled,
        (state, action: PayloadAction<UserData>) => {
          state.loading = false;
          state.data = action.payload;
        }
      )
      .addCase(getUserDetails.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { clearUser, setUserData } = userSlice.actions;
export default userSlice.reducer;
