import { StateCreator } from 'zustand';
import { FormStore } from '@/types/stores';

export const createProductionStandardFormSlice: StateCreator<
  FormStore,
  [],
  [],
  FormStore
> = (set): FormStore => ({
  formData: null,
  editMode: false,
  editIndex: null,

  setFormData: (data) =>
    set(() => ({
      formData: data,
    })),

  setEditMode: (mode, index) =>
    set(() => ({
      editMode: mode,
      editIndex: index,
    })),

  addDetail: (detail) =>
    set((state) => ({
      formData: state.formData
        ? {
            ...state.formData,
            details: [...state.formData.details, detail],
          }
        : null,
    })),

  updateDetail: (index, detail) =>
    set((state) => {
      if (!state.formData) return state;
      const newDetails = [...state.formData.details];
      newDetails[index] = detail;
      return {
        formData: {
          ...state.formData,
          details: newDetails,
        },
      };
    }),

  deleteDetail: (index) =>
    set((state) => {
      if (!state.formData) return state;
      const newDetails = [...state.formData.details];
      newDetails.splice(index, 1);
      return {
        formData: {
          ...state.formData,
          details: newDetails,
        },
      };
    }),

  clearCache: () =>
    set(() => ({
      formData: null,
      editMode: false,
      editIndex: null,
    })),
});
