<script lang="tsx">
import type { Moment } from 'moment'
import {
  computed,
  defineComponent, ref,
  type ComputedRef,
  type PropType, type Ref,
} from 'vue'
import { copyTooltip } from '../../../../helpers'
import { useClickOutside } from '../../../../lib'
import Calendar from '../../calendars/datetime-calendar/datetime-calendar.vue'

/**
 * Инпут для выбора даты и времени
 */
export default defineComponent({
  props: {
    /**
     * Состояние инпута
     */
    isDisabled: {
      type: Boolean,
      default: false,
    },
    /**
     * Показывать/не показывать заголовок
     */
    isShowLabel: {
      type: Boolean,
      default: true,
    },
    /**
     * Отметить как обязательный
     */
    isRequired: {
      type: Boolean,
      default: false,
    },
    /**
     * Можно/нельзя сбросить значение инпута
     */
    isClearable: {
      type: Boolean,
      default: true,
    },
    /**
     * Вариант отображения для таблицы
     */
    isForTable: {
      type: Boolean,
      default: false,
    },

    /**
     * Опция, запрещающая менять время
     */
    isFixedTime: {
      type: Boolean,
      default: false,
    },

    /**
     * Опция копирования значения
     */
    isWithCopy: {
      type: Boolean,
      default: false,
    },
    /**
     * Текст заголовка
     */
    label: {
      type: String,
      default: '',
    },
    /**
     * Плейсхолдер
     */
    placeholder: {
      type: String,
      default: '__.__.____',
    },
    /**
     * Массив ошибок
     */
    errors: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
    /**
     * Значение инпута
     */
    modelValue: {
      type: [Object, null] as PropType<Moment | null>,
      required: true,
    },
    /**
     * Формат отображения значения в инпуте
     */
    format: {
      type: String,
      default: 'DD.MM.YYYY, HH:mm',
    },
    /**
     * Описание
     */
    description: {
      type: String,
      default: '',
    },
    /**
     * Не закрывать датапикер после клика
     */
    closeCalendarOnClick: {
      type: Boolean,
      default: true,
    },

    /**
     * Функция изменения значения
     */
    onValueChange: {
      type: Function as PropType<(v: Moment | null) => void>,
      required: true,
    },
  },
  setup(props) {
    const isShowCalendar: Ref<boolean> = ref(false)

    const calendar: Ref<HTMLElement | null> = ref(null)
    const formattedValue: ComputedRef<string> = computed(() => props.modelValue?.format(props.format) ?? '')

    const showCalendar = (val: boolean) => {
      if (props.isDisabled && val === true) return

      isShowCalendar.value = val
    }

    const setDate = (val: Moment | null) => {
      if (props.onValueChange) {
        props.onValueChange(val)
      }
    }

    const copy = (event: MouseEvent) => {
      if (!props.isWithCopy) return

      copyTooltip(formattedValue.value, event.clientX + 10, event.clientY - 30)
    }

    const onClick = (event: MouseEvent) => {
      copy(event)

      if (props.closeCalendarOnClick || !isShowCalendar.value) showCalendar(!isShowCalendar.value)
    }

    useClickOutside(calendar, () => showCalendar(false))

    return () => (
      <div
        ref={calendar}
        class={`ark-ui-datetime-calendar-input ${props.isDisabled ? 'disabled' : ''} ${props.isWithCopy ? 'withCopy' : ''} ${props.errors.length ? 'invalid' : ''}`}

        onClick={onClick}
      >
        { props.label && props.isShowLabel && <div class="ark-ui-datetime-calendar-input-label">{ props.label }{ props.isRequired ? '*' : '' }</div> }

        { !props.isDisabled && (
          <div class='ark-ui-datetime-calendar-input-overlap' />
        ) }

        <div class={`ark-ui-datetime-calendar-input-wrap ${isShowCalendar.value ? 'is-opened' : ''} ${props.modelValue ? 'is-selected' : ''}`}>

          { props.isForTable && <div class='ark-ui-datetime-calendar-input-element'>{ props.placeholder }</div> }

          { !props.isForTable && (

            <input
              readonly={props.isDisabled}
              placeholder={props.placeholder}
              value={props.modelValue?.isValid() ? formattedValue.value : ''}

              type='text'
              class='ark-ui-datetime-calendar-input-element'
            />

          ) }

          {
            props.isClearable && props.modelValue
              ? <div onClick={() => setDate(null)} class='ark-ui-datetime-calendar-input-icon ark-ui-datetime-calendar-input-icon-clear' />
              : <div class='ark-ui-datetime-calendar-input-icon ark-ui-datetime-calendar-input-icon-calendar' />
          }

        </div>

        {
          !props.isDisabled && props.errors && props.errors.length > 0
            ? props.errors.map((error) => <div class='ark-ui-datetime-calendar-input-error'>{error}</div>)
            : props.description
              ? <div class="ark-ui-title ark-ui-description">{props.description}</div>
              : ''
        }

        { isShowCalendar.value && (

          <div class="ark-ui-datetime-calendar-input-calendar-container">
            { props.isForTable && (
              <div class="ark-ui-datetime-calendar-input-calendar-container-inputs">

                <input type="text" value={formattedValue.value} placeholder="__.__.____" disabled />

                { props.modelValue && <div onClick={() => setDate(null)} class="ark-ui-datetime-calendar-input-calendar-container-clear" /> }

              </div>
            ) }

            <Calendar isFixedTime={props.isFixedTime} date={props.modelValue} onSetDate={setDate} />
          </div>

        ) }
      </div>
    )
  },
})
</script>

<style lang="sass">
@import '../../../../styles/fonts.scss'
@import '../../../../styles/variables.scss'

.ark-ui-datetime-calendar-input
  position: relative

  &-wrap
    display: flex
    align-items: center
    position: relative

  &-element
    border-radius: 4px
    border: 1px solid #D3D5E5
    width: 100%
    height: 40px
    padding: 10px 16px
    box-sizing: border-box
    font-size: 14px

    &:focus
      outline: none

  &-icon
    position: absolute
    right: 16px
    top: 50%
    transform: translateY(-50%)
    width: 24px
    height: 24px
    display: block
    border-radius: 2px
    background: transparent
    background-position: center
    background-repeat: no-repeat
    cursor: pointer

    &-calendar
      background-image: url('./../../assets/datetime-calendar.svg')
      background-repeat: no-repeat

    &-clear
      cursor: pointer
      background-image: url('./../../assets/clear.svg')
      background-repeat: no-repeat
      z-index: $element

      &:hover
        background-image: url('./../../assets/clear-hover.svg')

  &-calendar-container
    position: absolute
    background-color: #fff
    margin-top: 4px
    z-index: $dropdown
    box-shadow: 0px 8px 16px 0px rgba(75, 77, 89, 0.08)
    border-radius: 4px

    &-inputs
      display: flex
      align-items: center
      justify-content: space-between
      box-sizing: border-box
      padding: 10px 16px

      input
        width: 75px
        border: none
        outline: none
        display: block

        font-size: 14px

        &[disabled=""]
          background: white

        &:focus
          border-bottom: 1px solid #21C2D1

    &-clear
      cursor: pointer
      background: url('./../../assets/clear.svg') center center no-repeat
      width: 16px
      height: 16px
      margin-left: 10px

  &-overlap
    position: absolute
    top: 0
    left: 0
    width: 100%
    height: 100%
    cursor: pointer
    z-index: $element

  &-error
    font-size: 12px
    color: $error-color
    margin-top: 4px

  &-label
    font-size: 12px
    color: $placeholder-grey
    margin-bottom: 8px

  &.withCopy
    cursor: copy !important

    input
      cursor: copy !important

  &.disabled
    .ark-ui-datetime-calendar-input
      &-element
        border-color: #F6F6FA !important
        background-color: #F6F6FA
        color: #585B69

      &-icon-calendar
        display: none

      &-label
        color: #585B69

  &:hover, &:focus
    .ark-ui-datetime-calendar-input
      &-element
        border-color: #A3A7B9

  &.invalid
    .ark-ui-datetime-calendar-input
      &-element
        border-color: $error-color

.default-table-header
  .ark-ui-datetime-calendar-input
    &-head-placeholder
      min-width: 40px
      margin-right: 13px
      overflow: hidden
      white-space: nowrap
      text-overflow: ellipsis
      color: #585B69
      font-size: 14px
      font-weight: 500
      line-height: 16px

    &-wrap
      &.is-selected
        .ark-ui-datetime-calendar-input-icon-calendar
          background-image: url('./../../assets/calendar-cyan.svg')
          background-repeat: no-repeat

      &.is-opened
        .ark-ui-datetime-calendar-input-icon-calendar
          background-image: url('./../../assets/datetime-calendar-dark.svg')
          background-repeat: no-repeat

    &-element
      border: none
      border-radius: 0
      padding: 16px
      background-color: transparent
      font-size: 14px
      font-weight: 500
      color: #585B69

    &-icon
      right: 12px

    &-calendar-container
      margin-top: 0

  &:has(.ark-ui-datetime-calendar-input-wrap.is-opened)
    background-color: #F0F1F7

  &:hover
    .ark-ui-datetime-calendar-input-icon-calendar
      background-image: url('./../../assets/datetime-calendar-dark.svg')
      background-repeat: no-repeat
</style>
