import { Button } from 'antd'
import { useEffect, useState } from 'react'
import { metas, labels, images } from './board'
import { BoardType, BoardTypeDesc } from 'store'
import { SelectMap, SelectFuse } from './modal'
import style from './style.module.scss'

import type { ShapeType, Board } from './board'
import type { RefObject } from 'react'

type SliderProps = {
  board: RefObject<Board>
  type: BoardType
  caseId: number
}
export const DfSlider = ({ board, type, caseId }: SliderProps) => {
  const [selectMode, setSelectMode] = useState(false)
  const [currentShape, setCurrentShape] = useState<ShapeType>()
  const getEle = (shapeType: ShapeType) => (
    <div 
      key={shapeType}
      className={style['df-slide-shape'] + (currentShape === shapeType ? ` ${style['active']}` : '')} 
      onClick={() => setCurrentShape(shapeType)}
    >
      <img src={metas[shapeType].icon} />
      <p>{metas[shapeType].desc}</p>
    </div>
  )
  const setBoardImage = async (blob: Blob) => {
    const url = URL.createObjectURL(blob)
    board.current?.setImage(url)
  }
  const SelectImage = type  === BoardType.map ? SelectMap : SelectFuse
  const renderSelect = selectMode && <SelectImage
    caseId={caseId}
    onClose={() => setSelectMode(false)} 
    onSave={setBoardImage}
  />

  useEffect(() => {
    const boardRef = board.current
    if (currentShape && boardRef) {
      const clickHandler = (ev: MouseEvent) => {
        const pos = boardRef.getPosByScreen({ x: ev.offsetX, y: ev.offsetY })
        boardRef.addShape(currentShape, pos)
        setCurrentShape(void 0)
      }
      const keyupHandler = (ev: KeyboardEvent) => {
        if (ev.key === 'Escape') {
          setCurrentShape(void 0)
        }
      }
      boardRef.el.addEventListener('click', clickHandler)
      document.documentElement.addEventListener('keyup', keyupHandler)

      return () => {
        boardRef.el.removeEventListener('click', clickHandler)
        document.documentElement.removeEventListener('keyup', keyupHandler)
      }
    }
  }, [currentShape, board])
  
  return (
    <div className={style['df-slide-content']}>
      { renderSelect }
      <h3>户型图</h3>
      <Button type="primary" block ghost  onClick={() => setSelectMode(true)}>设置{ BoardTypeDesc[type] }</Button>
      <h3>标注</h3>
      <div className={style['df-shape-layout']}>{ labels.map(getEle) }</div>
      <h3>图例</h3>
      <div className={style['df-shape-layout']}>{ images.map(getEle) }</div>
    </div>
  )
}

export default DfSlider