import { create } from 'zustand'
import type { CommCode } from '@/types/CommCode'

interface SuitableState {
  /* 공통코드 */
  suitableCommCode: Map<string, CommCode[]>
  /* 공통코드 설정 */
  setSuitableCommCode: (headCode: string, commCode: CommCode[]) => void

  /* 검색 상태 */
  isSearch: boolean
  /* 검색 상태 설정 */
  setIsSearch: (isSearch: boolean) => void

  /* 선택된 카테고리 */
  selectedCategory: string
  /* 선택된 카테고리 설정 */
  setSelectedCategory: (category: string) => void

  /* 검색 값 */
  searchValue: string
  /* 검색 값 설정 */
  setSearchValue: (value: string) => void

  /* 선택된 아이템 리스트 */
  selectedItems: number[]
  /* 선택된 아이템 추가 */
  addSelectedItem: (itemId: number) => void
  /* 선택된 아이템 제거 */
  removeSelectedItem: (itemId: number) => void
  /* 선택된 아이템 모두 제거 */
  clearSelectedItems: () => void
}

export const useSuitableStore = create<SuitableState>((set) => ({
  suitableCommCode: new Map() as Map<string, CommCode[]>,
  isSearch: false as boolean,
  selectedCategory: '' as string,
  searchValue: '' as string,
  selectedItems: [] as number[],

  /* 공통코드 설정 */
  setSuitableCommCode: (headCode: string, commCode: CommCode[]) =>
    set((state) => ({
      suitableCommCode: new Map(state.suitableCommCode).set(headCode, commCode),
    })),

  /* 검색 상태 설정 */
  setIsSearch: (isSearch: boolean) => set({ isSearch }),

  /* 선택된 카테고리 설정 */
  setSelectedCategory: (category: string) => set({ selectedCategory: category }),

  /* 검색 값 설정 */
  setSearchValue: (value: string) => set({ searchValue: value }),

  /* 선택된 아이템 추가 */
  addSelectedItem: (itemId: number) =>
    set((state) => ({
      selectedItems: state.selectedItems.some((i) => i === itemId) ? state.selectedItems : [...state.selectedItems, itemId],
    })),

  /* 선택된 아이템 제거 */
  removeSelectedItem: (itemId: number) =>
    set((state) => ({
      selectedItems: state.selectedItems.filter((i) => i !== itemId),
    })),

  /* 선택된 아이템 모두 제거 */
  clearSelectedItems: () => set({ selectedItems: [] }),
}))
