"use client"

import CustomModal from "./CustomModal"
import { Autocomplete, Box } from "@mantine/core"
import { useEffect, useState } from "react"
import { useLabelStore } from "../store"
import { useBottomToolsStore } from "../useBottomToolsStore"
import { usePaperStore } from "../usePaperStore"
import { useRightToolsStore } from "../useRightToolsStore"
import { safeClone } from "../utils/clone"

interface ComponentProps {
  open: boolean
  editId: number | null
  afterChange: (id: number) => void
  closeModal: () => void
}

const RightGroupEditModal = ({
  open,
  editId,
  afterChange,
  closeModal,
}: ComponentProps) => {
  const [items, setItems] = useState<string[]>([])
  const [inputValue, setInputValue] = useState(editId ? String(editId) : "")

  useEffect(() => {
    if (open) {
      const groupMap = useRightToolsStore
        .getState()
        .pathGroupMap.get(useBottomToolsStore.getState().activeImage)
      const currentImgIds = Array.from(groupMap?.keys() ?? [])
      const pathIds = useRightToolsStore.getState().pathGroupIds
      const ids = pathIds.filter((id) => !currentImgIds.includes(id))
      let maxId =
        useRightToolsStore
          .getState()
          .pathGroupIds.reduce((a, b) => Math.max(a, b), 0) + 1

      setTimeout(() => {
        setItems(
          Array.from(new Set([...ids, editId || maxId, maxId]))
            .filter((item): item is number => item !== null)
            .sort((a, b) => a - b)
            .map((item) => String(item))
        )
      }, 0)
    }
  }, [editId, open])

  const commitChange = (val: string) => {
    if (!val || !editId) return
    const id = Number(val)
    if (isNaN(id)) return

    const imageId = useBottomToolsStore.getState().activeImage
    const groupMap = useRightToolsStore.getState().pathGroupMap.get(imageId)

    if (groupMap?.has(id)) return

    const oldIds = groupMap?.get(editId) ?? []
    const labelData = safeClone(useLabelStore.getState().label)
    // update path
    let operationIds: any[] = []
    oldIds.forEach((childId) => {
      const childPath = usePaperStore.getState().getItemById(childId)!
      operationIds.push(childPath.data.operationId)
    })
    operationIds.forEach((operationId, index) => {
      if (labelData.get(imageId)?.get(operationId)?.length) {
        let result =
          labelData
            .get(imageId)
            ?.get(operationId)
            ?.map((item) =>
              item[0] !== oldIds[index]
                ? item
                : [item[0], item[1], { ...item[2], parentGroupId: id }, item[3]]
            ) || []
        labelData.get(imageId)?.set(operationId, result as any)
      }
    })
    // update groupMap
    groupMap?.set(id, oldIds)
    groupMap?.delete(editId)
    afterChange(id)
    useRightToolsStore.getState().pushPathGroupId(id)
    useLabelStore.getState().setLabel(labelData)
  }

  return (
    <CustomModal
      title="编辑群组"
      open={open}
      onCancel={closeModal}
      footer={null}
      width={200}
      centered>
      <Box w="100%" pb={8}>
        <Autocomplete
          value={inputValue}
          onChange={setInputValue}
          onBlur={() => commitChange(inputValue)}
          onOptionSubmit={(val) => {
            setInputValue(val)
            commitChange(val)
          }}
          data={items}
          w="100%"
        />
      </Box>
    </CustomModal>
  )
}

export default RightGroupEditModal
