<script setup>
import SecondaryButton from "@/components/Buttons/SecondaryButton.vue";
import ShipmentInfoModal from "@/components/ShipmentInfoModal.vue";
import { ref, onMounted } from "vue";

const props = defineProps({
  orderId: {
    type: [String, Number],
    required: true,
  },
});

const shipments = window.gcargo.shipments?.[props.orderId] || [];
const returneds = window.gcargo.returneds?.[props.orderId] || [];
const modals = ref([]);

onMounted(() => {
  shipments.forEach((shipment) => {
    modals[shipment.id] = false;
  });
});

const createPdfUrl = (base64) => {
  const pdfData = atob(base64);
  const arrayBuffer = new Uint8Array(pdfData.length);

  for (let i = 0; i < pdfData.length; i++) {
    arrayBuffer[i] = pdfData.charCodeAt(i);
  }

  return URL.createObjectURL(
    new Blob([arrayBuffer], { type: "application/pdf" }),
  );
};

returneds.forEach((returned) => {
  returned.pdfUrl = returned.pdf ? createPdfUrl(returned.pdf) : "";
});
</script>
<template>
  <div class="flex flex-col gap-4 items-center">
    <div v-if="shipments.length > 0" class="flex gap-2 items-center">
      <template v-for="shipment in shipments" :key="shipment.id">
        <img
          :src="shipment.cargo_company.logo"
          class="object-cover w-10 cursor-pointer"
          @click="modals[shipment.id] = !modals[shipment.id]"
        />
        <ShipmentInfoModal v-model="modals[shipment.id]" :shipment="shipment" />
      </template>
    </div>

    <div v-if="returneds.length > 0" class="flex gap-4 items-start">
      <div
        v-for="returned in returneds"
        :key="returned.id"
        class="flex flex-col items-center gap-1"
      >
        <SecondaryButton
          :link="returned.pdfUrl"
          :disabled="!returned.pdfUrl"
          :download="`iade-barkodu-${orderId}.pdf`"
        >
          İade Barkodu
          <arrow-down-tray-icon class="size-6" />
        </SecondaryButton>
      </div>
    </div>
  </div>
</template>
