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

import type { MetaShapeType, Board } from './board'
import type { RefObject } from 'react'
import type { Tagging } from 'api'

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<MetaShapeType>()
  const getEle = (shapeType: MetaShapeType) => {
    const Shape = shapes[shapeType]
    return (
      <div 
        key={shapeType}
        className={style['df-slide-shape'] + (currentShape === shapeType ? ` ${style['active']}` : '')} 
        onClick={() => setCurrentShape(shapeType)}
      >
        <Shape />
        <p>{metas[shapeType].desc}</p>
      </div>
    )
  }
  const setBoardImage = async (blob: Blob | null, taggings: Tagging[]) => {
    if (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) {
      console.log('read add', currentShape)
      const cleaup = boardRef.readyAddShape(
        currentShape,
        () => setCurrentShape(void 0)
      )
      const keyupHandler = (ev: KeyboardEvent) => {
        if (ev.key === 'Escape') {
          setCurrentShape(void 0)
          cleaup()
        }
      }
      document.documentElement.addEventListener('keyup', keyupHandler)

      return () => {
        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