<script setup>
import { ref, reactive, watch } from "vue";
import MdrSelect from "@/components/Mudur-Ui-Kit/MdrSelect.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import BarcodeModal from "@/components/BarcodeModal.vue";
import ShipmentListItem from "@/components/ShipmentListItem.vue";

import { useResourceStore } from "@/stores/ResourceStore";
import { useApiRequestStore } from "@/stores/ApiRequestStore";
import { storeToRefs } from "pinia";
import { successAlert, errorAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const orderData = window.gcargo.order_data;
const shipmentsData = reactive({
  list: window.gcargo.shipments || [],
  status: window.gcargo.shipment_status || "ready_for_shipment",
});
const cargoIntegrations = window.gcargo.cargo_integrations || [];
const warehouses = window.gcargo.warehouses || [];
const shipmentSettings = window.gcargo.shipment_setting || {};

const { shipment } = storeToRefs(useResourceStore());
const { store } = useResourceStore();
const { getPdf } = useApiRequestStore();

const errors = ref({});
const modals = ref([]);
const pdfUrlModal = ref(false);
const pdfUrl = ref("");

if (orderData) {
  const defaultCargoIntegration =
    cargoIntegrations.find((ci) => ci.is_default)?.id ||
    cargoIntegrations[0]?.id;
  const defaultWarehouse =
    warehouses.find((w) => w.is_default)?.id || warehouses[0]?.id;

  shipment.value = {
    ...orderData,
    ...shipmentSettings,
    customer: { ...orderData.customer },
    lines: [...orderData.lines],
    cargo_integration_id: defaultCargoIntegration,
    warehouse_id: defaultWarehouse,
    desi: orderData.desi,
    kg: orderData.kg,
    is_pay_at_door: orderData.is_pay_at_door,
    invoice_number: orderData.invoice_number,
    waybill_number: orderData.waybill_number,
    platform_id: orderData.platform_id,
    platform_d_id: orderData.platform_d_id,
    package_count: orderData.package_count,
  };
}

watch(
  () => shipmentsData.list,
  (list) => {
    list.forEach((shipmentItem) => {
      if (modals.value[shipmentItem.id] === undefined) {
        modals.value[shipmentItem.id] = false;
      }
    });
  },
  { immediate: true },
);

const createShipment = async () => {
  errors.value = {};
  if (!shipment.value) return;

  try {
    const result = await store({
      data: {
        resource: "shipments",
        data: shipment.value,
      },
      onValidationError: (response) => {
        errorAlert({ message: response.errors });
        errors.value = response.errors;
        return;
      },
    });

    if (result && result.id) {
      shipmentsData.list.push(result);

      if (
        shipmentsData.list.length === 1 &&
        shipmentsData.status === "ready_for_shipment"
      ) {
        shipmentsData.status = "partial_shipped";
      }
    }

    successAlert({ message: t("resource_added", [t("shipment")]) });
    pdfUrl.value = await getPdf({ data: { shipments: [result.id] } });
    pdfUrlModal.value = true;
  } catch (error) {
    console.error("Error creating shipment:", error);
    errors.value = { general: ["Gönderi oluşturulurken bir hata oluştu."] };
  }
};
</script>

<template>
  <div class="dokan-panel dokan-panel-default">
    <div class="dokan-panel-heading">
      <strong>Kargo Entegratör</strong>
    </div>
    <div class="dokan-panel-body">
      <div v-if="shipmentsData.list.length > 0" class="mb-4">
        <h4 class="text-sm font-semibold text-gray-700 mb-2">
          Mevcut Gönderiler ({{ shipmentsData.list.length }})
        </h4>
        <div class="space-y-4">
          <BarcodeModal v-model="pdfUrlModal" :pdf-url="pdfUrl"></BarcodeModal>

          <ShipmentListItem
            v-for="shipmentItem in shipmentsData.list"
            :key="shipmentItem.id"
            :shipment="shipmentItem"
            :modals="modals"
            :pdf-url-modal="pdfUrlModal"
            :pdf-url="pdfUrl"
            @update:pdf-url-modal="($event) => (pdfUrlModal = $event)"
            @update:pdf-url="($event) => (pdfUrl = $event)"
          />
        </div>
      </div>

      <div
        v-if="warehouses.length > 1 && shipmentsData.status !== 'all_shipped'"
        class="w-full mb-3"
      >
        <MdrSelect
          v-model="shipment.warehouse_id"
          :options="warehouses"
          value-key="id"
          text-key="name"
          :label="$t('warehouse')"
        />
      </div>
      <div
        v-if="
          cargoIntegrations.length > 1 && shipmentsData.status !== 'all_shipped'
        "
        class="w-full mb-3"
      >
        <MdrSelect
          v-model="shipment.cargo_integration_id"
          :options="cargoIntegrations"
          value-key="id"
          text-key="name"
          :label="$t('cargo_integration')"
        />
      </div>

      <PrimaryButton
        v-if="shipmentsData.status !== 'all_shipped'"
        class="!w-full"
        @click="createShipment()"
      >
        {{ $t("create_fast_shipment") }}
      </PrimaryButton>
    </div>
  </div>
</template>
