// store/location.slice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import Cookies from "js-cookie";

interface LocationState {
  id: string | null;
  is_default: boolean | null;
  phone_code: string | null;
  phone: string | null;
  country: {
    id: string | null;
    name: string | null;
  } | null;
  city: {
    id: string | null;
    name: string | null;
  } | null;

  district: {
    id: string | null;
    name: string | null;
  } | null;
  lng: string | null;
  lat: string | null;
  description: string | null;
  isLoading?: boolean;
}

const initialState: LocationState = {
  id: null,
  is_default: null,
  phone_code: null,
  phone: null,
  country: null,
  city: null,
  district: null,
  lng: null,
  lat: null,
  description: null,
  isLoading: true,
};

const locationSlice = createSlice({
  name: "location",
  initialState,
  reducers: {
    setLocation: (state, action: PayloadAction<LocationState>) => {
      state.id = action.payload.id;
      state.phone_code = action.payload.phone_code;
      state.phone = action.payload.phone;
      state.country = action.payload.country;
      state.city = action.payload.city;
      state.district = action.payload.district;
      state.lng = action.payload.lng;
      state.lat = action.payload.lat;
      state.description = action.payload.description;
      state.is_default = action.payload.is_default;
      state.isLoading = action.payload.isLoading;
      Cookies.set(
        "client_location",
        JSON.stringify({
          id: action.payload.id,
          lng: action.payload.lng,
          lat: action.payload.lat,
          description: action.payload.description,
          is_default: action.payload.is_default,
          phone_code: action.payload.phone_code,
          phone: action.payload.phone,
          country: action.payload.country,
          city: action.payload.city,
          district: action.payload.district,
        }),
        { expires: 30 },
      );
    },
    clearLocation: (state) => {
      state.id = null;
      state.phone_code = null;
      state.phone = null;
      state.country = null;
      state.city = null;
      state.district = null;
      state.lng = null;
      state.lat = null;
      state.description = null;
      state.is_default = null;
      state.isLoading = false;
      Cookies.remove("client_location");
    },
  },
});

export const { setLocation, clearLocation } = locationSlice.actions;
export default locationSlice.reducer;
