<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getWishlistAsyncComponent, setParamValue, getParamValue } from '@/helper'
import { ICollectionPayload } from '@/types'
import { useCollectionsStore } from '@/api'

const { getCollection } = useCollectionsStore()

const Lists = getWishlistAsyncComponent('components/Lists.vue')
const Items = getWishlistAsyncComponent('components/Items.vue')

const showItems = ref<boolean>(false)
const item = ref<ICollectionPayload>({
  key: '',
  user_id: 0,
  id: 0,
  name: '',
  description: '',
  status: '',
  is_default: false,
  is_public: false,
  url_code: '',
  items: [],
  emails: [],
  user_ids: [],
  allowed_roles: [],
  allowed_edit_emails: [],
})
const index = ref<number | null>(null)

const loadItems = async (record: any, idx: number) => {
  if (record !== 'new' && record?.id) {
    item.value = record
    showItems.value = true
    index.value = idx

    setParamValue('item', record.id)
  } else if (record === 'new') {
    showItems.value = true
    index.value = null

    setParamValue('item', '')
  }
}

const itemsAction = (action: string) => {
  if (action === 'close') {
    showItems.value = false
    item.value = {
      key: '',
      user_id: 0,
      id: 0,
      name: '',
      description: '',
      status: '',
      is_default: false,
      is_public: false,
      url_code: '',
      items: [],
      emails: [],
      user_ids: [],
      allowed_roles: [],
      allowed_edit_emails: [],
    }
    index.value = null

    setParamValue('item', '')
    setParamValue('add', '')
  }
}

const getItemData = async () => {
  const itemId = getParamValue('item')
  if (itemId) {
    const collection = await getCollection(itemId)
    item.value = collection.data
    showItems.value = true
    index.value = 0
  }
}

onMounted(() => {
  // Check if there is add param
  const add = getParamValue('add')
  if (add === 'new') {
    showItems.value = true
    index.value = null
  } else {
    getItemData()
  }
})
</script>

<template>
  <Lists v-if="!showItems && index === null" @loadItems="loadItems" />
  <Items v-else :item="item" :item-index="index" @action="itemsAction" />
</template>

<style scoped lang="scss">
.wishlist-app-layout {
  padding: 20px;
}
</style>