<script setup>
import { useMerchApi } from '@/api/merch.js'
import { onMounted, ref } from 'vue'
import router from '@/router/index.js'

const { getMerchDetails, deleteMerch } = useMerchApi()

const props = defineProps({
  merch_uuid: {
    type: String,
    required: true,
  },
})

const merchDetails = ref(null)
const loading = ref(true)
const error = ref(null)

const fetchMerch = async () => {
  try {
    const response = await getMerchDetails(props.merch_uuid)
    merchDetails.value = response.data

    if (!response.status === 400) {
      router.push({ name: 'collection' })
    }
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchMerch()
})

const showModal = ref(false)
const onDelete = () => {
  showModal.value = true
}

const confirmDelete = async () => {
  try {
    const response = await deleteMerch(props.merch_uuid)
    if (!response.status === 200) throw new Error('Network response was not ok')
    if (!response.status === 400) router.push({ name: 'collection' })
  } catch (error) {
    console.log(error)
  }
  showModal.value = false
  router.push({ name: 'collection' })
}
</script>

<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">Error: {{ error }}</div>
  <n-card v-else-if="merchDetails" :title="merchDetails.name">
    <n-divider title-placement="left">Main</n-divider>
    <p><strong>Uuid:</strong> {{ merchDetails.merch_uuid }}</p>
    <p><strong>Name:</strong> {{ merchDetails.name }}</p>

    <n-divider title-placement="left">Surugaya</n-divider>
    <p><strong>Link:</strong> {{ merchDetails.origin_surugaya.link }}</p>
    <p><strong>Cookie values:</strong> {{ merchDetails.origin_surugaya.cookie_values }}</p>

    <n-divider title-placement="left">Mandarake</n-divider>
    <p><strong>Link</strong> {{ merchDetails.origin_mandarake.link }}</p>
  </n-card>
  <div v-else>Not found</div>

  <div class="center-button-container">
    <n-button type="error" class="center-button" @click="onDelete">Delete</n-button>
  </div>

  <n-modal v-model:show="showModal" preset="dialog" title="Confirmation">
    <template #default>
      <p>Confirm delete</p>
    </template>
    <template #action>
      <n-button @click="confirmDelete" type="error">Ok</n-button>
      <n-button @click="showModal = false">Cancel</n-button>
    </template>
  </n-modal>
</template>

<style scoped></style>
