// user store
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

import { ICountries } from "../types/addressForm";

export type StoreType = {
  countries: ICountries[] | null;
  shippingCountries: ICountries[] | null;
  states: any[] | null;
  shippingStates: any[] | null;
  stores: any[] | null;
  cities: any[] | null;
  shippingCities: any[] | null;
  loading: boolean;
  loadingCities: boolean;
  loadingShippingCities: boolean;
  setCountries: (countries: ICountries[] | null) => void;
  setShippingCountries: (countries: ICountries[] | null) => void;
  setStates: (states: any[] | null) => void;
  setShippingStates: (shippingStates: any[] | null) => void;
  setStores: (stores: any[] | null) => void;
  setCities: (cities: any[] | null) => void;
  setShippingCities: (shippingCities: any[] | null) => void;
  setLoading: (newLoading: boolean) => void;
  setLoadingCities: (newLoading: boolean) => void;
  setShippingLoadingCities: (loadingShippingCities: boolean) => void;
};

export const countriesStore = create<StoreType>()(
  persist(
    (set, get) => ({
      countries: get()?.countries ?? null,
      shippingCountries: get()?.shippingCountries ?? null,
      states: [],
      shippingStates: [],
      cities: [],
      shippingCities: [],
      stores: [],
      loading: true,
      loadingCities: true,
      loadingShippingCities: true,
      setCountries: (newCountries: ICountries[]) =>
        set({ countries: newCountries }),
      setShippingCountries: (newCountries: ICountries[]) =>
        set({ shippingCountries: newCountries }),
      setStates: (newStates: any) => set({ states: newStates }),
      setShippingStates: (newStates: any) => set({ shippingStates: newStates }),
      setStores: (newStores: any) => set({ stores: newStores }),
      setCities: (newCities: any) => set({ cities: newCities }),
      setShippingCities: (newCities: any) => set({ shippingCities: newCities }),
      setLoading: (newLoading: any) => set({ loading: newLoading }),
      setLoadingCities: (newLoading: any) => set({ loadingCities: newLoading }),
      setShippingLoadingCities: (newLoading: any) =>
        set({ loadingShippingCities: newLoading }),
    }),
    {
      name: "countriesStore",
      storage: createJSONStorage(() => localStorage),
    },
  ),
);
