<script lang="tsx">
import { type Moment } from 'moment'
import {
  defineComponent, type PropType, computed, ref, type Ref, type ComputedRef,
} from 'vue'
import useClickOutside from '../../../../composables/use-click-outside'
import WeekCalendar from '../../calendars/week-calendar/week-calendar'

import './week-calendar-input.scss'

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

    /**
     * Текст заголовка
     */
    label: {
      type: String,
      default: '',
    },
    /**
     * Плейсхолдер
     */
    placeholder: {
      type: String,
      default: '',
    },
    /**
     * Массив ошибок
     */
    errors: {
      type: Array as PropType<string[]>,
      default: () => [],
    },
    /**
     * Начальная дата
     */
    start: {
      type: Object as PropType<Moment | undefined>,
    },
    /**
     * Конечная дата
     */
    end: {
      type: Object as PropType<Moment | undefined>,
    },
    /**
     * Функция установки начальной даты
     */
    onSetStart: {
      type: Function as PropType<(date: Moment | undefined) => void>,
      required: true,
    },
    /**
     * Функция установки конечной даты
     */
    onSetEnd: {
      type: Function as PropType<(date: Moment | undefined) => void>,
      required: true,
    },
  },
  setup(props) {
    const isShowCalendar: Ref<boolean> = ref(false)
    const isSelected = computed(() => props.start || props.end)

    const calendar: Ref<HTMLDivElement | null> = ref(null)

    const startDate: ComputedRef<string> = computed(() => (props.start ? props.start.format('DD.MM.YYYY') : ''))
    const endDate: ComputedRef<string> = computed(() => (props.end ? props.end.format('DD.MM.YYYY') : ''))

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

      isShowCalendar.value = val
    }

    const clear = () => {
      if (props.onSetStart) props.onSetStart(undefined)
      if (props.onSetEnd) props.onSetEnd(undefined)
    }

    const setStartDate = (val: Moment | undefined) => {
      if (props.onSetStart) {
        props.onSetStart(val)
      }
      if (val && endDate.value) isShowCalendar.value = false
    }

    const setEndDate = (val: Moment | undefined) => {
      if (props.onSetEnd) {
        props.onSetEnd(val)
      }
      if (val && startDate.value) isShowCalendar.value = false
    }

    const clearHandler = (e: MouseEvent) => {
      e.stopPropagation()
      clear()
    }

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

    return () => (

      <div ref={calendar} onClick={() => showCalendar(!isShowCalendar.value)} class={`ark-ui-week-calendar-input ${props.isDisabled ? 'disabled' : ''} ${props.errors.length ? 'invalid' : ''}`}>
        { props.label && props.isShowLabel && <div class="ark-ui-week-calendar-input-label">{props.label}</div> }

        <div class={`ark-ui-week-calendar-input-head ${isShowCalendar.value ? 'is-opened' : ''} ${isSelected.value ? 'is-selected' : ''}`}>
          {
            isSelected.value && !props.isForTable
              ? <div class="ark-ui-week-calendar-input-selected-value">
                <div>{startDate.value}</div>
                <div class="ark-ui-week-calendar-input-body-inputs-arrow" />
                <div>{endDate.value}</div>
              </div>
              : <div class="ark-ui-week-calendar-input-head-placeholder">
                { props.placeholder ? props.placeholder : (
                  <div class="ark-ui-week-calendar-input-default-placeholder">
                    <div>__.__.____</div>
                    <div class="ark-ui-week-calendar-input-body-inputs-arrow" />
                    <div>__.__.____</div>
                  </div>
                )}
              </div>
          }
          {
            isSelected.value && !props.isForTable
              ? <div onClick={clearHandler} class="ark-ui-week-calendar-input-icon clear" />
              : <div class="ark-ui-week-calendar-input-icon calendar" />
          }
        </div>

        { !props.isDisabled && props.errors.map((error) => <div class='ark-ui-week-calendar-input-error'>{error}</div>) }

        <div class="ark-ui-week-calendar-input-body" style={`display: ${isShowCalendar.value ? 'block' : 'none'};`}>
          <div onClick={(e) => e.stopPropagation()} class="ark-ui-week-calendar-input-body-container">
            <WeekCalendar
              start={props.start}
              end={props.end}
              onSetStart={setStartDate}
              onSetEnd={setEndDate}
            />
          </div>
        </div>
      </div>

    )
  },
})
</script>
