<script setup lang="ts">
import { __ } from '@wordpress/i18n'
import * as _ from 'lodash'
import { toRefs, ref, h } from 'vue'
import { useSettingsStore } from '@/stores/settings-store'
import { storeToRefs } from 'pinia'
import {
  getParamValue,
  setParamValue,
  getI18n,
} from '@/helper'
import SectionArea from '@/apps/settings/components/SectionArea.vue'

const props = defineProps({
  parentData: {
    type: Object,
    required: true
  },
  parentTab: {
    type: String,
    required: true,
  },
})
const { parentData, parentTab } = toRefs(props)

const settingsStore = useSettingsStore()
const {
  isLoading,
  externalLinks,
  inputValues,
} = storeToRefs(settingsStore)

const childTabs = parentData
const sortedTabs = ref<any>(_.sortBy(childTabs.value, (obj) => obj.sort))
const parent = parentTab
const tabClass = 'stw-child-tab'
const urlParam = getParamValue('tab-child')
const firstTab = ref<any>(Object.values(sortedTabs.value)?.[0] ?? '')
const activeKey = ref(urlParam ?? firstTab.value.key ?? '')

const emit = defineEmits(['fieldData'])
const handleFieldData = (data: object) => {
  Object.entries(data).forEach(([key, value]) => {
    inputValues.value[key] = value
  })

  emit('fieldData', inputValues.value)
}

const renderTabTitle = (tabkey: any, tab: any) => {
  const isLink = ref(tab.link !== undefined)
  const isExternal = ref(tab.external ? true : false)
  const target = isExternal.value ? '_blank' : '_self'
  const withBg = ref(tab?.with_background ? 'tab-with-bg' : '')
  if (!isLink.value) {
    return h('span', { class: 'tab-child-item ' + withBg.value }, tab.label)
  } else {
    if (!(tabkey in externalLinks.value)) {
      externalLinks.value[tabkey] = tab.link
    }
    return h('a', { class: 'tab-child-item', href: tab.link, target: target }, tab.label)
  }
}

const setActiveSection = (key: string) => {
  if (!(key in externalLinks.value)) {
    setParamValue('tab-child', key)
    activeKey.value = key
  }
}
</script>

<template>
  <div class="stwlite-tw-max-w-7xl stwlite-tw-mx-auto stwlite-tw-px-4 sm:stwlite-tw-px-6 lg:stwlite-tw-px-8 stwlite-tw-pb-8 stwlite-tw-pt-0">
    <div class="stwlite-tw-flex stwlite-tw-gap-8">
      <div class="stwlite-tw-w-64 stwlite-tw-flex-shrink-0">
        <div class="stwlite-tw-bg-white stwlite-tw-rounded-lg stwlite-tw-shadow-sm stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-overflow-hidden stwlite-tw-border-solid">
          <div class="stwlite-tw-p-4 stwlite-tw-bg-gray-50 stwlite-tw-border-0 stwlite-tw-border-b stwlite-tw-border-gray-200 stwlite-tw-border-solid">
            <h3 class="stwlite-tw-font-medium stwlite-tw-text-gray-900 stwlite-tw-m-0">{{ getI18n('settings', __( 'Settings', 'saveto-wishlist-lite-for-woocommerce' )) }}</h3>
          </div>
          <nav class="stwlite-tw-p-2">
              <button
                v-for="tab in sortedTabs"
                :key="tab.key"
                @click="setActiveSection(tab.key)"
                :class="[ 'stwlite-tw-w-full stwlite-tw-flex stwlite-tw-items-center stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-transition-colors stwlite-tw-border-0 stwlite-tw-cursor-pointer stwlite-tw-align-middle', activeKey === tab.key ? 'stwlite-tw-bg-blue-50 stwlite-tw-text-blue-700 stwlite-tw-border-r-2 stwlite-tw-border-blue-700' : 'stwlite-tw-bg-transparent stwlite-tw-text-gray-700 hover:stwlite-tw-bg-gray-50', ]"
                type="button"
              >
                <span v-html="tab.icon" class="stwlite-tw-mr-3 stwlite-tw-align-middle" />
                <span class="stwlite-tw-align-middle stwlite-tw-text-sm">{{ tab.label }}</span>
              </button>
          </nav>
        </div>
      </div>

      <div class="stwlite-tw-flex-1">
        <div v-for="tab in sortedTabs" :key="tab.key">
          <div v-if="activeKey === tab.key" :class="tab.key">
            <div v-if="tab?.link != null">
              <h3>{{ getI18n('redirectLoading', __( 'You are redirecting to a page. Please wait...', 'saveto-wishlist-lite-for-woocommerce' )) }}</h3>
            </div>
            <div v-else class="stwlite-tw-space-y-8">
              <div>
                <h2 class="stwlite-tw-capitalize stwlite-tw-text-xl stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-1 stwlite-tw-mt-0">{{ tab.label }}</h2>
              </div>
              <SectionArea
                :parent-tab="parent"
                :child-tab="tab.key"
                :section-data="tab.sections"
                @field-data="handleFieldData"
              />
              <br>
              <button
                v-if="tab.no_save !== true"
                type="submit"
                :class="[ 'stwlite-tw-bg-blue-600 stwlite-tw-text-white stwlite-tw-px-4 stwlite-tw-py-2 stwlite-tw-rounded-md stwlite-tw-font-medium stwlite-tw-text-sm hover:stwlite-tw-bg-blue-700 stwlite-tw-transition-colors stwlite-tw-border-0 stwlite-tw-cursor-pointer stwlite-tw-mb-3', isLoading ? 'stwlite-tw-bg-gray-400 stwlite-tw-cursor-not-allowed hover:stwlite-tw-bg-gray-400' : 'stwlite-tw-bg-blue-600 hover:stwlite-tw-bg-blue-700', ]"
                :disabled="isLoading"
              >
                <span v-if="isLoading">{{ getI18n('saving', __('Saving...', 'saveto-wishlist-lite-for-woocommerce')) }}</span>
                <span v-else>{{ getI18n('submitText', __('Save Changes', 'saveto-wishlist-lite-for-woocommerce')) }}</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
