<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useResourceStore } from "@/stores/ResourceStore";
import { useApiRequestStore } from "@/stores/ApiRequestStore";
import { errorAlert, successAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { useUiStore } from "@/stores/UiStore";
import { useI18n } from "vue-i18n";
import { storeToRefs } from "pinia";
import BarcodeModal from "@/components/BarcodeModal.vue";
import Spinner from "./Partials/Spinner.vue";
import { useOrderStore } from "@/stores/OrderStore";
const { getMappedData } = useOrderStore();

const { t } = useI18n();
const { loading } = storeToRefs(useUiStore());
const { store } = useResourceStore();
const { getPdf } = useApiRequestStore();
const statuses = computed(() => window.gcargo.statuses);
const cargoIntegrations = computed(() => window.gcargo.cargo_integrations);

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

const pdfUrlModal = ref(false);
const pdfUrl = ref();
const shipments = ref(window.gcargo.shipments?.[props.orderId] || []);
const shipmentStatus = ref(
  window.gcargo.order_shipment_statuses?.[props.orderId],
);

const create = async (id) => {
  const res = await store({
    data: {
      resource: "shipments",
      data: {
        ...(await getMappedData(props.orderId)),
        cargo_integration_id: id,
      },
    },
    onValidationError: (response) => {
      errorAlert({ message: response.message });
    },
  });
  successAlert({ message: t("resource_added", [t("shipment")]) });
  shipmentStatus.value = "all_shipped";
  shipments.value.push(res);
  pdfUrl.value = await getPdf({ data: { shipments: [res.id] } });
  pdfUrlModal.value = true;
};

const printPdf = async (id) => {
  pdfUrl.value = await getPdf({ data: { shipments: [id] } });
  pdfUrlModal.value = true;
};

const dropdownOpen = ref(false);
const dropdownRef = ref(null);

const toggleDropdown = () => {
  dropdownOpen.value = !dropdownOpen.value;
};

const selectCargoIntegration = async (cargoIntegrationId) => {
  dropdownOpen.value = false;
  await create(cargoIntegrationId);
};

const handleClickOutside = (event) => {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target)) {
    dropdownOpen.value = false;
  }
};

onMounted(() => {
  document.addEventListener("click", handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>
<template>
  <div v-if="shipments.length > 0" class="flex flex-col flex-1 gap-2 w-full">
    <button
      v-for="shipment in shipments"
      :key="shipment.id"
      type="button"
      :class="`text-xs px-2 py-1 flex items-center justify-center gap-1 shipment-status-type box-border ${shipment.status} rounded-full w-fit border hover:border-primary-600`"
      @click="printPdf(shipment.id)"
    >
      <Spinner v-if="loading" />
      <printer-icon v-else class="w-3 h-3" />
      <span class="break-words">
        {{ statuses[shipment.status] }} -
        {{ shipment.cargo_company.title }}
      </span>
    </button>
    <BarcodeModal
      v-model="pdfUrlModal"
      :pdf-url="pdfUrl"
      :disable-reload="true"
    ></BarcodeModal>
  </div>

  <div v-else-if="shipmentStatus && shipmentStatus !== 'all_shipped'">
    <button
      v-if="cargoIntegrations.length === 1"
      type="button"
      class="button flex items-center gap-2"
      :disabled="loading"
      @click="create(cargoIntegrations[0].id)"
    >
      <Spinner v-if="loading" />
      <img
        v-else
        :src="cargoIntegrations[0].company_info.logo"
        :alt="cargoIntegrations[0].name"
        class="w-6 h-6 object-contain rounded"
      />
      <span>Gönderi Oluştur</span>
    </button>

    <template v-else>
      <div ref="dropdownRef" class="relative">
        <button
          type="button"
          class="flex items-center gap-2 px-2 bg-white border border-gray-300 rounded hover:border-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-500 min-w-[150px]"
          :disabled="loading"
          @click="toggleDropdown"
        >
          <div
            v-if="loading"
            class="flex items-center h-5 justify-center w-full"
          >
            <Spinner />
          </div>
          <div v-else class="flex items-center justify-between gap-2 w-full">
            <span>Gönderi Oluştur</span>
            <svg
              class="w-4 h-4 transition-transform"
              :class="{ 'rotate-180': dropdownOpen }"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </div>
        </button>

        <div
          v-if="dropdownOpen"
          class="absolute z-10 mt-1 bg-white border border-gray-300 rounded shadow-lg w-fit"
        >
          <template
            v-for="cargoIntegration in cargoIntegrations"
            :key="cargoIntegration.id"
          >
            <button
              type="button"
              class="w-full px-3 py-2 text-left flex items-center gap-2 hover:bg-gray-100 transition-colors"
              :disabled="loading"
              @click="selectCargoIntegration(cargoIntegration.id)"
            >
              <img
                :src="cargoIntegration.company_info.logo"
                :alt="cargoIntegration.name"
                class="w-6 h-6 object-contain rounded"
              />
              <span>{{ cargoIntegration.name }}</span>
            </button>
            <hr
              v-if="
                cargoIntegration !==
                cargoIntegrations[cargoIntegrations.length - 1]
              "
              class="h-px my-1 bg-gray-200 border-0 dark:bg-gray-700"
            />
          </template>
        </div>
      </div>
    </template>
  </div>
</template>
