import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { Area, City, Country } from "@/types/global";

interface AddressState {
  country: Country | null;
  /** استان (جدول cities) */
  city: City | null;
  /** شهر (جدول areas) */
  area: Area | null;
  isCountrySelectModalOpen: boolean;
  updateCountry: (country: Country) => void;
  updateCity: (city: City | null | undefined) => void;
  updateArea: (area: Area | null | undefined) => void;
  /** ذخیره یکجای کشور/استان/شهر تا persist ناقص نماند */
  saveLocation: (payload: {
    country: Country;
    city: City;
    area: Area;
  }) => void;
  deleteCountry: () => void;
  openCountrySelectModal: () => void;
  closeCountrySelectModal: () => void;
}

const noopStorage = {
  getItem: () => null,
  setItem: () => {},
  removeItem: () => {},
};

const useAddressStore = create<AddressState>()(
  persist(
    (set) => ({
      country: null,
      city: null,
      area: null,
      isCountrySelectModalOpen: false,
      updateCountry: (country) => set({ country }),
      updateCity: (city) => set({ city: city ?? null }),
      updateArea: (area) => set({ area: area ?? null }),
      saveLocation: ({ country, city, area }) =>
        set({
          country,
          city,
          area,
          isCountrySelectModalOpen: false,
        }),
      deleteCountry: () => set({ country: null }),
      openCountrySelectModal: () => set({ isCountrySelectModalOpen: true }),
      closeCountrySelectModal: () => set({ isCountrySelectModalOpen: false }),
    }),
    {
      name: "address",
      skipHydration: true,
      storage: createJSONStorage(() =>
        typeof window === "undefined" ? noopStorage : localStorage
      ),
    }
  )
);

export default useAddressStore;
