<script setup lang="ts">
import { ref } from 'vue'
import { getSavetoWishlistObj } from '@/config'
import { useSettingsStore } from '@/stores/settings-store'
import { storeToRefs } from 'pinia'
import {
  sendRequest,
  getParamValue,
  setParamValue,
  isTabExists,
} from '@/helper'
import ChildTabs from '@/apps/settings/components/ChildTabs.vue'
import Notification from '@/helper/Notification.vue'

import { TabGroup, TabList, Tab, TabPanels, TabPanel } from '@headlessui/vue'

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

const tabSettings = getSavetoWishlistObj.settings
const tabLists = tabSettings.tabs
const urlParam = getParamValue('tab')
const isTabExist = isTabExists(urlParam, tabLists)
const firstTab = ref<any>(Object.values(tabLists)?.[0] ?? '')
const activeKey = ref(isTabExist ?? firstTab.value.key)
const notificationMessage = ref<string>('')
const notificationType = ref<string>('')
const notificationMessageTitle = ref<string>('')

const handleFieldData = (data: object) => {
  Object.entries(data).forEach(([key, value]) => {
    inputValues.value[key] = value
  });
}
const onSubmit = async(e: any) => {
  isLoading.value = true
  const payload: { key: string; value: any }[] = []
  for (const [key, val] of Object.entries(inputValues.value)) {
    let value = <any>val
    if ( typeof val === 'object' && val !== null ) {
      value = JSON.stringify(val)
    }
    payload.push({ key, value })
  }

  try {
    const response = await sendRequest(payload)
    if (response) {
      notificationMessageTitle.value = response.title
      notificationMessage.value = response.message
      notificationType.value = response.type

      isLoading.value = false
    }
  } catch (error) {
    console.error(error)
  }
}

defineExpose({
  onSubmit
})

const handleTabChange = (key: string) => {
  setParamValue('tab', key)
  setParamValue('tab-child', '')
}

const closeNotification = () => {
  notificationMessage.value = ''
}

const hasMultipleTabs = Array.isArray(tabLists) ? tabLists.length > 1 : Object.keys(tabLists).length > 1
</script>

<template>
  <div class="stwlite-tw-w-full">
    <form id="stw-admin-tab-settings" method="post" @submit.prevent="onSubmit">
      <TabGroup>
        <div v-if="hasMultipleTabs" class="stwlite-tw-max-w-7xl stwlite-tw-mx-auto stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-4 stwlite-tw-px-3 stwlite-tw-pb-0 stwlite-tw-pt-6 stwlite-tw-border-0">
          <TabList class="stwlite-tw-flex stwlite-tw-space-x-1 stwlite-tw-flex-1 stwlite-tw-rounded-md stwlite-tw-bg-white stwlite-tw-px-6 stwlite-tw-pt-6 stwlite-tw-shadow-sm stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-border-solid">
            <Tab
              v-for="(tab, tabkey) in tabLists"
              v-model="activeKey"
              as="template"
              :key="tabkey"
              v-slot="{ selected }"
            >
              <button
                @click="handleTabChange(tabkey.toString())"
                :class="[ 'stwlite-tw-px-8 stwlite-tw-py-2.5 stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-border-0 stwlite-tw-cursor-pointer stwlite-tw-bg-transparent focus:stwlite-tw-outline-none', selected ? 'stwlite-tw-text-blue-700 stwlite-tw-border-b-2 stwlite-tw-border-blue-700' : 'stwlite-tw-border-b-2 stwlite-tw-border-transparent', ]"
              >
                {{ tab.label }}
              </button>
            </Tab>
          </TabList>
        </div>
        
        <TabPanels
          :class="[ 'stwlite-tw-mt-2', !hasMultipleTabs ? 'stwlite-tw-pt-8' : '', ]"
        >
          <TabPanel
            v-for="(tab, tabkey) in tabLists"
            :key="tabkey"
            :class="[ 'stwlite-tw-rounded-xl stwlite-tw-p-3', 'stwlite-tw-ring-white/60 stwlite-tw-ring-offset-2 stwlite-tw-ring-offset-blue-400', ]"
          >
            <ChildTabs
              :parent-tab="tabkey.toString()"
              :parent-data="tab.child"
              @field-data="handleFieldData"
            />
          </TabPanel>
        </TabPanels>
      </TabGroup>
    </form>
  </div>

  <Notification
    v-if="notificationMessage"
    :message="notificationMessage"
    :type="notificationType"
    :messageTitle="notificationMessageTitle"
    @closeNotification="closeNotification"
  />
</template>
