<template>
  <div
    class="link-panel"
    id="linkPanel"
    :class="{ closed: !isOpen, mobile: isMobileDevice }"
    :style="{ height: isMobileDevice ? '70%' : isHeaderDisabled ? '100%' : 'calc(100% - 88px)'}"
    >
    <div class="sidebar-title">
      {{ $t('linkPanel.linkTo') }}
      <Close v-if="isMobileDevice" class="close-button" @click="closePanel" />
    </div>
    <div class="sidebar-tabs-header">
      <Button
        :className="activePanelTab === 'URL' ? 'active' : ''"
        :isActive="activePanelTab === 'URL'"
        data-element="URL"
        @click="setActivePanelTab('URL')"
      >
        <span>{{ $t('linkPanel.url') }}</span>
      </Button>
      <Button
        :className="activePanelTab === 'PAGE' ? 'active' : ''"
        :isActive="activePanelTab === 'PAGE'"
        data-element="PAGE"
        @click="setActivePanelTab('PAGE')"
      >
        <span>{{ $t('linkPanel.goToPages') }}</span>
      </Button>
      <Button
        :className="activePanelTab === 'EMAIL' ? 'active' : ''"
        :isActive="activePanelTab === 'EMAIL'"
        data-element="EMAIL"
        @click="setActivePanelTab('EMAIL')"
      >
        <span>{{ $t('linkPanel.email') }}</span>
      </Button>
    </div>

    <div class="sidebar-content">
      <!-- Url -->
      <div class="input-container" :class="{ hidden: activePanelTab !== 'URL' }">
        <input type="text" placeholder="https://www.compdf.com" v-model="urlValue" name="link">
        <EmptyInput v-show="urlValue" @click="empty" />
      </div>

      <!-- Page -->
      <div class="input-container" :class="{ hidden: activePanelTab !== 'PAGE' }">
        <input type="text" pattern="\d*" :placeholder="`1~${totalPages}`" v-model="pageValue" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))" name="link">
        <EmptyInput v-show="pageValue" @click="empty" />
      </div>

      <!-- Email -->
      <div class="input-container" :class="{ hidden: activePanelTab !== 'EMAIL' }">
        <input type="text" placeholder="support@compdf.com" v-model="emailValue" name="link">
        <EmptyInput v-show="emailValue" @click="empty" />
      </div>

      <div class="save rect-button blue" :class="{ disabled: !saveAvailable() }" @click="save">{{ $t('linkPanel.go') }}</div>
    </div>
  </div>
</template>

<script setup>
  import { computed, watch, ref } from 'vue'
  import { useViewerStore } from '@/stores/modules/viewer'
  import { useDocumentStore } from '@/stores/modules/document'
  import core from '@/core'
  import { isMobileDevice } from '@/helpers/device'

  const { isHeaderDisabled } = defineProps(['isHeaderDisabled'])
  const useViewer = useViewerStore()
  const useDocument = useDocumentStore()

  const activePanelTab = ref('URL')
  const isOpen = computed(() => useViewer.isElementOpen('linkPanel'))
  const activeTool = computed(() => useDocument.getActiveTool)
  const currentPage = computed(() => useViewer.getCurrentPage)
  const totalPages = computed(() => useDocument.getTotalPages)

  let urlValue = ref('')
  let pageValue = ref('')
  let emailValue = ref('')

  watch(() => activeTool.value, (newValue, oldValue) => {
    if (newValue !== 'link') {
      useViewer.closeElement('linkPanel')
    }
  })

  watch(() => isOpen.value, (newValue, oldValue) => {
    if (newValue) {
      useViewer.closeElement('pageModePanel')
      activePanelTab.value = urlValue.value ? 'URL' : pageValue.value ? 'PAGE' : emailValue.value ? 'EMAIL' : 'URL'
    }
  })

  watch(() => pageValue.value, (newValue, oldValue) => {
    const regex = /^\d+$/
    if ((newValue !== '' && (newValue > totalPages.value || newValue <= 0 || !regex.test(newValue)))) {
      pageValue.value = oldValue
    }
  })

  const setActivePanelTab = (tab) => {
    activePanelTab.value = tab
  }

  const saveAvailable = () => {
    return ((activePanelTab.value === 'URL' && validateLink(urlValue.value)) || (activePanelTab.value === 'PAGE' && pageValue.value) || (activePanelTab.value === 'EMAIL' && validateEmail(emailValue.value)))
  }

  const validateEmail = (email) => {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailPattern.test(email)
  }

  const validateLink = (link) => {
    const linkPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
    return linkPattern.test(link)
  }

  const save = () => {
    if (activePanelTab.value === 'URL') {
      // const start = urlValue.value.startsWith('http://') || urlValue.value.startsWith('https://') || urlValue.value.startsWith('ftp://')
      // useDocument.setPropertyPanel({ 'url': start ? urlValue.value : 'https://' + urlValue.value })
      useDocument.setPropertyPanel({ 'destPage': '', 'url': urlValue.value })
    } else if (activePanelTab.value === 'PAGE') {
      useDocument.setPropertyPanel({ 'url': '', 'destPage': pageValue.value })
    } else if (activePanelTab.value === 'EMAIL') {
      const start = emailValue.value.startsWith('mailto:')
      useDocument.setPropertyPanel({ 'destPage': '', 'url': start ? emailValue.value : 'mailto:' + emailValue.value })
    }
    useViewer.closeElement('linkPanel')
  }

  const updateProperty = (props) => {
    if (props) {
      if (props.url && props.url.startsWith('mailto:')) {
        emailValue.value = props.url.replace('mailto:', '')
        urlValue.value = ''
        pageValue.value = ''
        activePanelTab.value = 'email'
      } else if (props.url) {
        urlValue.value = props.url
        emailValue.value = ''
        pageValue.value = ''
        activePanelTab.value = 'URL'
      } else if (props.destPage) {
        pageValue.value = props.destPage
        urlValue.value = ''
        emailValue.value = ''
        activePanelTab.value = 'PAGE'
      } else {
        pageValue.value = ''
        urlValue.value = ''
        emailValue.value = ''
        activePanelTab.value = 'URL'
      }
      useViewer.openElement('linkPanel')
    } else {
      useViewer.closeElement('linkPanel')
    }
  }
  core.addEvent('linkPanelChange', updateProperty)

  const empty = () => {
    if (activePanelTab.value === 'URL') {
      urlValue.value = ''
    } else if (activePanelTab.value === 'PAGE') {
      pageValue.value = ''
    } else if (activePanelTab.value === 'EMAIL') {
      emailValue.value = ''
    }
  }

  const closePanel = () => {
    useViewer.closeElement('linkPanel')
  }
</script>

<style lang="scss">
  .hidden {
    display: none;
  }
  .link-panel {
    position: fixed;
    right: 0;
    z-index: 3;
    display: flex;
    flex-direction: column;
    height: calc(100% - 88px);
    overflow: hidden;
    transition: transform .3s ease-in-out;
    background-color: var(--c-side-bg);
    border-left: 1px solid var(--c-side-header-border);
    &.closed {
      transform: translateX(100%);
    }
    a {
      text-decoration: none;
    }
    .sidebar-tabs-header {
      display: flex;
      align-items: center;
      background-color: var(--c-right-side-header-bg);
      .button {
        flex: 1;
        margin: 0;
        padding: 12px 0;
        border-radius: initial;
        color: var(--c-right-side-header-text);
        &:not(.disabled):hover {
          background-color: var(--c-right-side-header-bg);
        }
        &:not(.disabled).active {
          background-color: var(--c-right-side-header-active);
          color: var(--c-white);
        }
        span {
          font-size: 12px;
          line-height: 16px;
        }
      }
      .divider {
        margin-right: 0;
      }
    }
    .sidebar-title {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 36px;
      font-size: 14px;
      line-height: 17px;
      font-weight: 700;
      color: var(--c-right-side-header-text);
    }
    .sidebar-content {
      margin-top: 16px;
      width: 100%;
      flex: 1;
      overflow: hidden;
    }
    .input-container {
      margin: 0 16px;
      position: relative;
      input {
        padding: 0 20px 0 8px;
        width: 100%;
        height: 24px;
        background: var(--c-right-side-content-fillbox-bg);
        border: 1px solid var(--c-right-side-content-fillbox-border);
        border-radius: 1px;
        font-size: 16px;
        line-height: 20px;
        color: var(--c-text);
        font-family: 'Helvetica';
        &::placeholder {
          font-size: 14px;
          color: var(--c-text);
          opacity: 0.6;
        }
      }
      svg {
        position: absolute;
        right: 4px;
        top: 4px;
        cursor: pointer;
      }
    }
    .save {
      margin: 40px auto;
      width: 120px;
      &.disabled {
        opacity: 1;
        border-color: #999;
        background-color: #999;
      }
    }
  }

  .link-panel.mobile {
    background-color: var(--c-side-header-bg);
    border-left: none;
    bottom: 0;
    border-radius: 10px 10px 0 0;
    box-shadow: 0px 4px 32px 0px var(--c-doc-editor-popup-shadow);

    &.closed {
      transform: translateY(100%);
      box-shadow: none;
    }

    .close-button {
      position: absolute;
      right: 14px;
    }
  }

  @media screen and (max-width: 640px) {
    .link-panel {
      width: 100vw;
    }
  }
  @media screen and (min-width: 641px) {
    .link-panel {
      width: 260px;
    }
  }
</style>