// @flow

import React, { useReducer, useEffect } from "react"
import MainLayout from "../MainLayout"
import SettingsProvider from "../SettingsProvider"

import combineReducers from "./reducers/combine-reducers.js"
import generalReducer from "./reducers/general-reducer.js"
import imageReducer from "./reducers/image-reducer.js"
import historyHandler from "./reducers/history-handler.js"

import useEventCallback from "use-event-callback"
import makeImmutable, { without } from "seamless-immutable"

export const Annotator = ({
  images,
  allowedArea,
  selectedImage = images && images.length > 0 ? images[0].src : undefined,
  showPointDistances,
  pointDistancePrecision,
  showTags = true,
  enabledTools = [
    "select",
    "create-point",
    "create-box",
    "create-polygon",
    "create-expanding-line",
    "show-mask",
  ],
  selectedTool = "select",
  regionTagList = [],
  regionClsList = [],
  imageTagList = [],
  imageClsList = [],
  taskDescription,
  fullImageSegmentationMode = false,
  RegionEditLabel,
  onExit,
  changeSelectedIndex,
  onStateChange,
  selectedIndex,
  openAlert,
  init_idx,
  displayTools,
  onNextImage,
  onPrevImage,
  autoSegmentationOptions = { type: "autoseg" }}) => {
  if (!images)
    return '이미지를 선택하세요'
  const annotationType = images ? "image" : null
  const [state, dispatchToReducer] = useReducer(
    historyHandler(
      combineReducers(
        annotationType === "image" ? imageReducer : null,
        generalReducer
      )
    ),
    makeImmutable({
      annotationType,
      showTags,
      allowedArea,
      showPointDistances,
      pointDistancePrecision,
      selectedTool,
      fullImageSegmentationMode: fullImageSegmentationMode,
      autoSegmentationOptions,
      mode: null,
      taskDescription,
      showMask: true,
      labelImages: imageClsList.length > 0 || imageTagList.length > 0,
      regionClsList,
      regionTagList,
      imageClsList,
      imageTagList,
      enabledTools,
      history: [],
      ...(annotationType === "image"
        ? {
            selectedImage,
            images : images.slice(0, 1),
            images_ : images,
            selectedImageFrameTime:
              images && images.length > 0 ? images[0].frameTime : undefined,
          }
        : {
            
          }),
    })
  )

  const dispatch = useEventCallback((action) => {
    if (action.type === "HEADER_BUTTON_CLICKED") {
      if (["Exit", "Done", "Save", "Complete"].includes(action.buttonName)) {
        return onExit(without(state, "history"))
      } else if (action.buttonName === "Next" && onNextImage) {
        return onNextImage(without(state, "history"))
      } else if (action.buttonName === "Prev" && onPrevImage) {
        return onPrevImage(without(state, "history"))
      }
    }
    dispatchToReducer(action)
  })

  const onRegionClassAdded = useEventCallback((cls) => {
    dispatchToReducer({
      type: "ON_CLS_ADDED",
      cls: cls,
    })
  })

  useEffect(() => {
    if (!selectedImage) return
    dispatchToReducer({
      type: "SELECT_IMAGE",
      image: state.images.find((img) => img.src === selectedImage),
    })

  }, [selectedImage])

  return (
    <SettingsProvider>
      <MainLayout
        RegionEditLabel={RegionEditLabel}
        alwaysShowNextButton={Boolean(onNextImage)}
        alwaysShowPrevButton={Boolean(onPrevImage)}
        state={state}
        dispatch={dispatch}
        onRegionClassAdded={onRegionClassAdded}
        changeSelectedIndex={changeSelectedIndex}
        onStateChange={onStateChange}
        selectedIndex={selectedIndex}
        openAlert={openAlert}
        init_idx={init_idx}
        displayTools={displayTools}
      />
    </SettingsProvider>
  )
}

export default Annotator
