<template>
  <button
    @click="handleDownload"
    :disabled="downloading"
    class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border border-gray-300 text-gray-700 hover:bg-gray-50 disabled:opacity-50"
  >
    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
    </svg>
    {{ downloading ? 'Se descarca...' : label }}
  </button>
</template>

<script setup>
import { ref } from 'vue'
import { usePdf } from '../../composables/usePdf.js'

const props = defineProps({
  type: { type: String, required: true, validator: v => ['deviz', 'invoice'].includes(v) },
  orderId: { type: String, default: null },
  invoiceId: { type: String, default: null },
  nrComanda: { type: String, default: '' },
  nrFactura: { type: String, default: '' },
  label: { type: String, default: 'PDF' },
})

const { downloadDevizPdf, downloadInvoicePdf } = usePdf()
const downloading = ref(false)

async function handleDownload() {
  downloading.value = true
  try {
    if (props.type === 'deviz') {
      await downloadDevizPdf(props.orderId, props.nrComanda)
    } else {
      await downloadInvoicePdf(props.invoiceId, props.nrFactura)
    }
  } catch (e) {
    alert(e.message)
  } finally {
    downloading.value = false
  }
}
</script>
