import { ArrowLeftOutlined, ArrowRightOutlined } from "@ant-design/icons"
import { Button } from "antd"
import { useNavigate, fillRoutePath, RoutePath, usePathData } from "router"
import { saveAs } from 'utils'
import style from './style.module.scss'
import { 
  useSelector, 
  boardStatus, 
  useDispatch, 
  insertBoard, 
  updateBoard, 
  currentBoard, 
  BoardTypeDesc, 
  BoardType 
} from "store"

import type { RefObject } from "react"
import type { Board } from "./board"

type HeaderProps = {
  board: RefObject<Board>
  type: BoardType
}
const Header = ({ board, type }: HeaderProps) => {
  const path = usePathData()
  const status = useSelector(boardStatus)
  const current = useSelector(currentBoard)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const exportPng = async () => {
    if (board.current) {
      const blob = await board.current.export()
      saveAs(blob, '现场图.png')
    }
  }
  const save = async () => {
    if (current.id === -1) {
      const data = await dispatch(insertBoard({ type, data: current })).unwrap()
      navigate(
        fillRoutePath(RoutePath.drawFile, { ...path as any, id: data.id.toString() }),
        { replace: true }
      )
    } else {
      dispatch(updateBoard({ id: current.id, data: current }))
    }
  }

  return (
    <>
      <div className={style['df-header-left']}>
        <span className={`${style['df-header-back']} icon`} onClick={() => navigate(-1)}>
          <ArrowLeftOutlined />
          返回
        </span>
      </div>
      <h1 className={style['df-header-center']}>
        创建{ BoardTypeDesc[type] }
      </h1>
      <div className={style['df-header-right']}>
        <div className={style['df-header-action']}>
          <ArrowLeftOutlined 
            className={!status.canBack ? 'disabled':  'icon'} 
            onClick={() => dispatch({ type: 'board/backoff' })} 
          />
          <ArrowRightOutlined 
            className={!status.canForward ? 'disabled': 'icon'} 
            onClick={() => dispatch({ type: 'board/forward' })} 
          />
        </div>
        <Button type="primary" size="middle" onClick={save}>保存</Button>
        <Button type="default" size="middle" onClick={exportPng}>导出</Button>
      </div>
    </>
  )
}

export default Header
