import { DrawerUISlice } from '@/types/stores';
import { StateCreator } from 'zustand';
import { ReactNode } from 'react';

export const createDrawerUISlice: StateCreator<
  DrawerUISlice,
  [],
  [],
  DrawerUISlice
> = (set, get, api) => ({
  // event flag untuk memicu formik validate
  triggerValidate: false,

  // dibalik untuk memicu event
  toggleValidate: () => {
    const current = get().triggerValidate;
    set({ triggerValidate: !current });
  },

  // sistem subscriber sederhana agar form bisa listen perubahan flag
  subscribeValidate: (callback: () => void) => {
    let prev = get().triggerValidate;

    const unsub = api.subscribe((state) => {
      if (state.triggerValidate !== prev) {
        prev = state.triggerValidate;
        callback();
      }
    });

    return unsub;
  },

  isValid: false,
  setIsValid: (isValid: boolean) => set({ isValid }),
  subscribeIsValid: (callback: (isValid: boolean) => void) => {
    return api.subscribe((state) => {
      callback(Boolean(state.isValid));
    });
  },

  expandedDrawerOpen: false,
  setExpandedDrawerOpen: (open: boolean) => set({ expandedDrawerOpen: open }),

  expandedDrawerContent: null as ReactNode | null,
  setExpandedDrawerContent: (content: ReactNode) =>
    set({ expandedDrawerContent: content }),

  isNextStep: false,
  setIsNextStep: (isNextStep: boolean) => set({ isNextStep }),
});
