import { create } from "zustand"
import { persist } from "zustand/middleware"

export interface SelectedObjectEditTarget {
  imageId: string
  operationId: string
  objectId: number
  objectType: string
}

interface KeyboardStore {
  ctrl: boolean
  setCtrl: (v: boolean) => void
  shift: boolean
  setShift: (v: boolean) => void
  showShortcutGuide: boolean
  setShowShortcutGuide: (v: boolean) => void
  shortcutGuidePosition: {
    x: number
    y: number
  }
  setShortcutGuidePosition: (position: { x: number; y: number }) => void
  shortcutGuideCollapsedSections: Record<string, boolean>
  toggleShortcutGuideSection: (sectionId: string) => void
  drawAction: "none" | "add" | "subtract"
  setDrawAction: (mode: "none" | "add" | "subtract") => void
  selectedObjectEditTarget: SelectedObjectEditTarget | null
  setSelectedObjectEditTarget: (target: SelectedObjectEditTarget | null) => void
  copyDataIds: number[] // ctrl + c 复制数据
  setCopyDataIds: (ids: number[]) => void
}

export const useKeyboardStore = create<KeyboardStore>()(
  persist(
    (set) => ({
      ctrl: false,
      shift: false,
      showShortcutGuide: false,
      shortcutGuidePosition: {
        x: 16,
        y: 16,
      },
      shortcutGuideCollapsedSections: {},
      drawAction: "none",
      selectedObjectEditTarget: null,
      copyDataIds: [],
      setCtrl: (v) => set((state) => ({ ...state, ctrl: v })),
      setShift: (v) => set((state) => ({ ...state, shift: v })),
      setShowShortcutGuide: (v) =>
        set((state) => ({ ...state, showShortcutGuide: v })),
      setShortcutGuidePosition: (position) =>
        set((state) => ({
          ...state,
          shortcutGuidePosition: {
            x: Math.round(position.x),
            y: Math.round(position.y),
          },
        })),
      toggleShortcutGuideSection: (sectionId) =>
        set((state) => ({
          ...state,
          shortcutGuideCollapsedSections: {
            ...state.shortcutGuideCollapsedSections,
            [sectionId]: !state.shortcutGuideCollapsedSections[sectionId],
          },
        })),
      setDrawAction: (mode) =>
        set((state) => ({ ...state, drawAction: mode })),
      setSelectedObjectEditTarget: (target) =>
        set((state) => ({ ...state, selectedObjectEditTarget: target })),
      setCopyDataIds: (ids) =>
        set((state) => ({ ...state, copyDataIds: ids })),
    }),
    {
      name: "keyboard-store",
      partialize: (state) => ({
        shortcutGuidePosition: state.shortcutGuidePosition,
        shortcutGuideCollapsedSections: state.shortcutGuideCollapsedSections,
      }),
    }
  )
)
