import { defineStore } from "pinia";
import { LocalStorage, date } from "quasar";
import { ref, watch } from "vue";

const STORAGE_KEY = "service_package_cart";

const loadPersistedCart = () => {
  const persisted = LocalStorage.getItem(STORAGE_KEY);

  if (!persisted || !Array.isArray(persisted.items)) {
    return { items: [], provider: null };
  }

  const today = date.formatDate(Date.now(), "YYYY-MM-DD");

  const items = persisted.items.filter(
    (item) => item && item.date && item.date >= today,
  );

  return {
    items,
    provider: items.length ? (persisted.provider ?? null) : null,
  };
};

export const useServicePackageStore = defineStore("servicePackage", () => {
  const persisted = loadPersistedCart();

  const items = ref(persisted.items);

  const provider = ref(persisted.provider);

  const lastCreatedGroup = ref(null);

  watch(
    [items, provider],
    () => {
      LocalStorage.set(STORAGE_KEY, {
        items: items.value,
        provider: provider.value,
      });
    },
    { deep: true },
  );

  const addItem = (item) => {
    items.value.push(item);
  };

  const removeItem = (index) => {
    items.value.splice(index, 1);

    if (!items.value.length) {
      provider.value = null;
    }
  };

  const setProvider = (value) => {
    provider.value = value ? { ...value } : null;
  };

  const clear = () => {
    items.value = [];
    provider.value = null;
    LocalStorage.remove(STORAGE_KEY);
  };

  const setLastCreatedGroup = (group) => {
    lastCreatedGroup.value = group;
  };

  return {
    items,
    provider,
    lastCreatedGroup,
    addItem,
    removeItem,
    setProvider,
    clear,
    setLastCreatedGroup,
  };
});
