<script setup>
import { toast } from 'bulma-toast'

const props = defineProps({
  params: Object
})

const isUploading = ref(false)
const isResetting = ref(false)

const isUploaded = computed(() => {
  if (!props.params?.data) return false
  return props.params.data.isUploadToAmazon === true || props.params.data.isUploadToAmazon === 'Y'
})

const isAmazonSource = computed(() => {
  return String(props.params?.data?.marketplaceKey || '').toLowerCase() === 'amazon'
})

const upload = async () => {
  if (isUploading.value || !props.params?.data?.id) return
  if (!isAmazonSource.value) {
    toast({ message: 'Only invoices from an Amazon order source can be uploaded.', type: 'is-warning', duration: 4000 })
    return
  }

  isUploading.value = true
  try {
    const res = await $fetch('/api/invoices/amazon-upload', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: { ids: [props.params.data.id] }
    })

    if (Number(res.status) >= 400) {
      toast({ message: res.message || 'Failed to upload to Amazon', type: 'is-danger', duration: 5000 })
    } else {
      toast({ message: res.message || 'Successfully uploaded to Amazon', type: 'is-success', duration: 5000 })
      if (props.params.data) {
        props.params.data.isUploadToAmazon = true
        props.params.data.uploadDateAmazon = new Date().toISOString()
      }
      props.params.api?.refreshCells({ rowNodes: [props.params.node], force: true })
    }
  } catch (err) {
    toast({ message: 'Failed to upload to Amazon', type: 'is-danger', duration: 5000 })
  } finally {
    isUploading.value = false
  }
}

const reset = async () => {
  if (isResetting.value || !props.params?.data?.id) return

  const confirmation = confirm('Reset Amazon status for this invoice?')
  if (!confirmation) return

  isResetting.value = true
  try {
    const res = await $fetch('/api/invoices/amazon-reset', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: { ids: [props.params.data.id] }
    })

    if (Number(res.status) >= 400) {
      toast({ message: res.message || 'Failed to reset Amazon status', type: 'is-danger', duration: 5000 })
    } else {
      toast({ message: res.message || 'Successfully reset Amazon status', type: 'is-success', duration: 5000 })
      if (props.params.data) {
        props.params.data.isUploadToAmazon = false
        props.params.data.uploadDateAmazon = null
      }
      props.params.api?.refreshCells({ rowNodes: [props.params.node], force: true })
    }
  } catch (err) {
    toast({ message: 'Failed to reset Amazon status', type: 'is-danger', duration: 5000 })
  } finally {
    isResetting.value = false
  }
}
</script>

<template>
  <div v-if="params?.data" class="status-cell">
    <span v-if="isUploading || isResetting" class="tf-icon ti ti-loader ti-sm fg-gray"></span>
    <span
      v-else-if="isUploaded"
      class="tf-icon ti ti-circle-check ti-sm fg-success cursor-pointer"
      title="Uploaded to Amazon - Click to Reset"
      @click="reset"
    ></span>
    <span
      v-else-if="!isAmazonSource"
      class="tf-icon ti ti-minus ti-sm"
      style="color: lightgrey; opacity: 0.5;"
      title="Not an Amazon order source"
    ></span>
    <span
      v-else
      class="tf-icon ti ti-circle-x ti-sm cursor-pointer"
      style="color: lightgrey;"
      title="Upload to Amazon"
      @click="upload"
    ></span>
  </div>
  <span v-else class="no-action">-</span>
</template>

<style scoped>
.status-cell {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.fg-success {
  color: #28a745;
}

.fg-danger {
  color: #dc3545;
}

.fg-gray {
  color: lightgrey;
}

.cursor-pointer {
  cursor: pointer;
}

.no-action {
  color: lightgrey;
}
</style>
