import { makeAutoObservable, runInAction } from "mobx";
import { City } from "../CityStore";

class SelectedCityStore {
  selectedCity: City | null = null;
  isLocked: boolean = false;
  cityVersion: number = 0;

  constructor() {
    makeAutoObservable(this);
    this.initialize();
  }

  private initialize() {
    const storedCity = localStorage.getItem("selectedCity");
    if (storedCity) {
      try {
        this.selectedCity = JSON.parse(storedCity);
      } catch (error) {
        console.error("Error parsing stored city:", error);
        localStorage.removeItem("selectedCity");
      }
    }
  }

  setSelectedCity = (city: City | null) => {
    runInAction(() => {
      this.selectedCity = city;
      this.cityVersion += 1;
      if (city) {
        localStorage.setItem("selectedCity", JSON.stringify(city));
      } else {
        localStorage.removeItem("selectedCity");
      }
    });
  };

  setIsLocked = (locked: boolean) => {
    runInAction(() => {
      this.isLocked = locked;
    });
  };

  clearSelectedCity = () => {
    this.setSelectedCity(null);
  };

  get selectedCityId() {
    return this.selectedCity?.id || null;
  }

  get selectedCityName() {
    return this.selectedCity?.name || null;
  }
}

export const selectedCityStore = new SelectedCityStore();
