import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { CheckoutStoreType } from "../types/Types";

const initialState = {
  isSelectedAddress: false,
  selectedAddressId: null,
  isSelectedPayment: false,
  isSelectedShipment: false,
  deliveryType: "0",
  paymentType: "0",
  tableNumber: 0,
  carAddress: null as {
    carModel: string;
    carColor: string;
    plateNumber: string;
  } | null,
  paymentDesc: "",
  paymentAttachments: [] as string[],
  lastUpdated: null as number | null,
};

export const useCheckoutStore = create<CheckoutStoreType>()(
  persist(
    (set) => ({
      ...initialState,
      setIsSelectedAddress: (value) =>
        set({ isSelectedAddress: value, lastUpdated: Date.now() }),
      setSelectedAddressId: (value) =>
        set({ selectedAddressId: value, lastUpdated: Date.now() }),
      setIsSelectedPayment: (value) =>
        set({ isSelectedPayment: value, lastUpdated: Date.now() }),
      setIsSelectedShipment: (value) =>
        set({ isSelectedShipment: value, lastUpdated: Date.now() }),
      setDeliveryType: (value) =>
        set({ deliveryType: value, lastUpdated: Date.now() }),
      setPaymentType: (value) =>
        set({ paymentType: value, lastUpdated: Date.now() }),
      setTableNumber: (value) =>
        set({ tableNumber: value, lastUpdated: Date.now() }),
      setCarAddress: (value) =>
        set({ carAddress: value, lastUpdated: Date.now() }),
      setPaymentDesc: (value) =>
        set({ paymentDesc: value, lastUpdated: Date.now() }),
      setPaymentAttachments: (value) =>
        set({ paymentAttachments: value, lastUpdated: Date.now() }),
      setLastUpdated: (value) => set({ lastUpdated: value }),
      clear: () => set({ ...initialState }),
    }),
    {
      name: "checkout-storage",
      storage: createJSONStorage(() => localStorage),
    }
  )
);

// چک خودکار برای پاک کردن بعد از 2 ساعت
if (typeof window !== "undefined") {
  const TWO_HOURS = 2 * 60 * 60 * 1000; // 2 ساعت به میلی‌ثانیه

  const checkAndClear = () => {
    const stored = localStorage.getItem("checkout-storage");
    if (stored) {
      try {
        const parsed = JSON.parse(stored);
        const state = parsed.state;
        if (state?.lastUpdated) {
          const now = Date.now();
          const timeDiff = now - state.lastUpdated;
          if (timeDiff >= TWO_HOURS) {
            useCheckoutStore.getState().clear();
          }
        }
      } catch {
        // در صورت خطا در parse، store را پاک می‌کنیم
        useCheckoutStore.getState().clear();
      }
    }
  };

  // چک در زمان لود شدن
  checkAndClear();

  // چک هر 5 دقیقه
  setInterval(checkAndClear, 5 * 60 * 1000);
}
