<template>
  <ps-popper
    ref="popper"
    v-model:visible="showPicker"
    effect="light"
    manual-mode
    trigger="click"
    :show-arrow="false"
    :offset="0"
    transition="ps-zoom-in-top"
    :gpu-acceleration="false"
    :popper-class="`ps-color-picker__panel ps-color-dropdown ${popperClass}`"
    :stop-popper-mouse-event="false"
  >
    <template #default>
      <div v-click-outside="hide">
        <div class="ps-color-dropdown__main-wrapper">
          <hue-slider
            ref="hue"
            class="hue-slider"
            :color="color"
            vertical
          />
          <sv-panel ref="svPanel" :color="color" />
        </div>
        <alpha-slider v-if="showAlpha" ref="alpha" :color="color" />
        <predefine
          v-if="predefine"
          ref="predefine"
          :color="color"
          :colors="predefine"
        />
        <div class="ps-color-dropdown__btns">
          <span class="ps-color-dropdown__value">
            <ps-input
              v-model="customInput"
              :validate-event="false"
              size="mini"
              @keyup.enter="handleConfirm"
              @blur="handleConfirm"
            />
          </span>
          <ps-button
            size="mini"
            type="text"
            class="ps-color-dropdown__link-btn"
            @click="clear"
          >
            {{ t('ps.colorpicker.clear') }}
          </ps-button>
          <ps-button
            plain
            size="mini"
            class="ps-color-dropdown__btn"
            @click="confirmValue"
          >
            {{ t('ps.colorpicker.confirm') }}
          </ps-button>
        </div>
      </div>
    </template>
    <template #trigger>
      <div
        :class="[
          'ps-color-picker',
          colorDisabled ? 'is-disabled' : '',
          colorSize ? `ps-color-picker--${ colorSize }` : ''
        ]"
      >
        <div v-if="colorDisabled" class="ps-color-picker__mask"></div>
        <div class="ps-color-picker__trigger" @click="handleTrigger">
          <span class="ps-color-picker__color" :class="{ 'is-alpha': showAlpha }">
            <span
              class="ps-color-picker__color-inner"
              :style="{
                backgroundColor: displayedColor
              }"
            ></span>
            <span v-if="!modelValue && !showPanelColor" class="ps-color-picker__empty ps-icon-close"></span>
          </span>
          <span v-show="modelValue || showPanelColor" class="ps-color-picker__icon ps-icon-arrow-down"></span>
        </div>
      </div>
    </template>
  </ps-popper>
</template>

<script lang="ts">
import type { PropType } from 'vue'
import { computed, defineComponent, inject, nextTick, onMounted, provide, reactive, ref, watch } from 'vue'
import type { ComputedRef } from '@vue/reactivity'
import { ClickOutside } from '@present-ui/directives'
import Color from './color'
import SvPanel from './components/sv-panel.vue'
import HueSlider from './components/hue-slider.vue'
import AlphaSlider from './components/alpha-slider.vue'
import Predefine from './components/predefine.vue'
import PsPopper from '@present-ui/popper'
import PsButton from '@present-ui/button'
import PsInput from '@present-ui/input'
import { t } from '@present-ui/locale'
import { UPDATE_MODEL_EVENT } from '@present-ui/utils/constants'
import { useGlobalConfig } from '@present-ui/utils/util'
import { isValidComponentSize } from '@present-ui/utils/validators'
import type { PsFormContext, PsFormItemContext } from '@present-ui/form'
import { psFormItemKey, psFormKey } from '@present-ui/form'
import debounce from 'lodash/debounce'

interface IUseOptions {
  currentColor: ComputedRef<string>
}

const OPTIONS_KEY = Symbol()

export const useOptions = () => {
  return inject<IUseOptions>(OPTIONS_KEY)
}

export default defineComponent({
  name: 'PsColorPicker',
  components: {
    PsPopper,
    PsInput,
    SvPanel,
    HueSlider,
    AlphaSlider,
    PsButton,
    Predefine,
  },
  directives: {
    ClickOutside,
  },
  props: {
    modelValue: String,
    showAlpha: Boolean,
    colorFormat: String,
    disabled: Boolean,
    size: {
      type: String as PropType<ComponentSize>,
      validator: isValidComponentSize,
    },
    popperClass: String,
    predefine: Array,
  },
  emits: ['change', 'active-change', UPDATE_MODEL_EVENT],
  setup(props, { emit }) {
    const ELEMENT = useGlobalConfig()
    const psForm = inject(psFormKey, {} as PsFormContext)
    const psFormItem = inject(psFormItemKey, {} as PsFormItemContext)

    const hue = ref(null)
    const svPanel = ref(null)
    const alpha = ref(null)
    const popper = ref(null)
    // data
    const color = reactive(new Color({
      enableAlpha: props.showAlpha,
      format: props.colorFormat,
    }))
    const showPicker = ref(false)
    const showPanelColor = ref(false)
    const customInput = ref('')
    // computed
    const displayedColor = computed(() => {
      if (!props.modelValue && !showPanelColor.value) {
        return 'transparent'
      }
      return displayedRgb(color, props.showAlpha)
    })
    const colorSize = computed(() => {
      return props.size || psFormItem.size || ELEMENT.size
    })
    const colorDisabled = computed(() => {
      return props.disabled || psForm.disabled
    })

    const currentColor = computed(() => {
      return !props.modelValue && !showPanelColor.value ? '' : color.value
    })
    // watch
    watch(() => props.modelValue, newVal => {
      if (!newVal) {
        showPanelColor.value = false
      } else if (newVal && newVal !== color.value) {
        color.fromString(newVal)
      }
    })
    watch(() => currentColor.value, val => {
      customInput.value = val
      emit('active-change', val)
      // showPanelColor.value = true
    })

    watch(() => color.value, () => {
      if (!props.modelValue && !showPanelColor.value) {
        showPanelColor.value = true
      }
    })

    // methods
    function displayedRgb(color, showAlpha) {
      if (!(color instanceof Color)) {
        throw Error('color should be instance of _color Class')
      }

      const { r, g, b } = color.toRgb()
      return showAlpha
        ? `rgba(${ r }, ${ g }, ${ b }, ${ color.get('alpha') / 100 })`
        : `rgb(${ r }, ${ g }, ${ b })`
    }

    function setShowPicker(value) {
      showPicker.value = value
    }

    const debounceSetShowPicker = debounce(setShowPicker, 100)

    function hide() {
      debounceSetShowPicker(false)
      resetColor()
    }

    function resetColor() {
      nextTick(() => {
        if (props.modelValue) {
          color.fromString(props.modelValue)
        } else {
          showPanelColor.value = false
        }
      })
    }

    function handleTrigger() {
      if (colorDisabled.value) return
      debounceSetShowPicker(!showPicker.value)
    }

    function handleConfirm() {
      color.fromString(customInput.value)
    }

    function confirmValue() {
      const value = color.value
      emit(UPDATE_MODEL_EVENT, value)
      emit('change', value)
      psFormItem.formItemMitt?.emit('ps.form.change', value)
      debounceSetShowPicker(false)
      // check if modelValue change, if not change, then reset color.
      nextTick(() => {
        const newColor = new Color({
          enableAlpha: props.showAlpha,
          format: props.colorFormat,
        })
        newColor.fromString(props.modelValue)
        if (!color.compare(newColor)) {
          resetColor()
        }
      })
    }

    function clear() {
      debounceSetShowPicker(false)
      emit(UPDATE_MODEL_EVENT, null)
      emit('change', null)
      if (props.modelValue !== null) {
        psFormItem.formItemMitt?.emit('ps.form.change', null)
      }
      resetColor()
    }

    onMounted(() => {
      if (props.modelValue) {
        color.fromString(props.modelValue)
        customInput.value = currentColor.value
      }
    })
    watch(() => showPicker.value, () => {
      nextTick(() => {
        hue.value?.update()
        svPanel.value?.update()
        alpha.value?.update()
      })
    })

    provide<IUseOptions>(OPTIONS_KEY, {
      currentColor,
    })

    return {
      color,
      colorDisabled,
      colorSize,
      displayedColor,
      showPanelColor,
      showPicker,
      customInput,
      handleConfirm,
      hide,
      handleTrigger,
      clear,
      confirmValue,
      t,
      hue,
      svPanel,
      alpha,
      popper,
    }
  },
})
</script>
