<script setup>
import MdrModal from "@/components/Mudur-Ui-Kit/MdrModal.vue";
import MdrFormField from "@/components/Mudur-Ui-Kit/MdrFormField.vue";
import MdrCheckboxField from "@/components/Mudur-Ui-Kit/MdrCheckboxField.vue";
import MdrSelect from "@/components/Mudur-Ui-Kit/MdrSelect.vue";
import MdrAccordion from "@/components/Mudur-Ui-Kit/MdrAccordion.vue";
import MdrAccordionItem from "@/components/Mudur-Ui-Kit/MdrAccordionItem.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import SecondaryButton from "@/components/Buttons/SecondaryButton.vue";
import DangerButton from "@/components/Buttons/DangerButton.vue";
import BarcodeModal from "@/components/BarcodeModal.vue";
import CountrySelect from "@/components/CountrySelect.vue";
import MdrTooltip from "@/components/Mudur-Ui-Kit/MdrTooltip.vue";
import MdrBadge from "@/components/Mudur-Ui-Kit/MdrBadge.vue";
import { useResourceStore } from "@/stores/ResourceStore";
import { useSettingsStore } from "@/stores/SettingsStore";
import { storeToRefs } from "pinia";
import { ref, onBeforeMount, computed } from "vue";
import { successAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { useI18n } from "vue-i18n";
import { useApiRequestStore } from "@/stores/ApiRequestStore.js";
import { shipmentSettingFields } from "@/utils/fields";

const { t } = useI18n();
const adminUrl = window.gcargo.admin_url;
const autoShipmentError = window.gcargo.auto_shipment_error;
const { shipment } = storeToRefs(useResourceStore());
const { cargoIntegrations, warehouses } = useResourceStore();
const { apiKey } = useSettingsStore();
const { store } = useResourceStore();
const { getPdf, fixAddress } = useApiRequestStore();
const modal = ref(false);
const errors = ref({});
const pdfUrlModal = ref(false);
const pdfUrl = ref();

onBeforeMount(() => {
  shipment.value = {
    ...window.gcargo.shipment,
  };
});

const showCityCode = computed(() => {
  return shipment.value.customer.country_code !== "TR";
});

const cityLabel = computed(() => {
  return shipment.value.customer.country_code !== "TR" ? t("state") : t("city");
});

const districtLabel = computed(() => {
  return shipment.value.customer.country_code !== "TR"
    ? t("city")
    : t("district");
});

const create = async () => {
  errors.value = {};
  shipment.value.lines = shipment.value.lines.filter(
    (line) => line.quantity > 0,
  );
  shipment.value = await store({
    data: {
      resource: "shipments",
      data: shipment.value,
    },
    onValidationError: (response) => {
      errors.value = response.errors;
      modal.value = true;
    },
  });
  modal.value = false;
  successAlert({ message: t("resource_added", [t("shipment")]) });
  pdfUrl.value = await getPdf({ data: { shipments: [shipment.value.id] } });
  pdfUrlModal.value = true;
};
const changeQty = (index, op) => {
  let quantitiy = shipment.value.lines[index].quantity;
  quantitiy = quantitiy + op;
  if (quantitiy < 0) {
    quantitiy = 0;
  } else if (quantitiy > shipment.value.lines[index].sold_qty) {
    quantitiy = shipment.value.lines[index].sold_qty;
  }
  shipment.value.lines[index].weight =
    shipment.value.lines[index].base_weight * quantitiy;

  shipment.value.kg = shipment.value.lines.reduce(
    (acc, line) => acc + line.weight,
    0,
  );

  shipment.value.lines[index].quantity = quantitiy;
};

const fix = async () => {
  const addressData = {
    address: shipment.value.customer.address,
    district: shipment.value.customer.district,
    city: shipment.value.customer.city,
    country: shipment.value.customer.country,
    postcode: shipment.value.customer.postcode,
  };

  const response = await fixAddress({ data: addressData });
  if (response) {
    shipment.value.customer = {
      ...shipment.value.customer,
      city: response.formattedAddress.city || shipment.value.customer.city,
      district:
        response.formattedAddress.district || shipment.value.customer.district,
      address:
        response.formattedAddress.fullAddress ||
        shipment.value.customer.address,
      country:
        response.formattedAddress.country || shipment.value.customer.country,
      postcode:
        response.formattedAddress.postcode || shipment.value.customer.postcode,
    };
  }
};

const showPackageCount = computed(() => {
  return shipment.value.package_type === "box";
});

const getShipmentOptions = (model) => {
  const field = shipmentSettingFields(t).find((f) => f.model === model);
  return field ? field.options : [];
};
</script>

<template>
  <div
    v-if="apiKey"
    class="flex flex-col items-center justify-center gap-3 w-full py-2"
  >
    <PrimaryButton class="!w-full" @click="create()"
      >{{ $t("create_fast_shipment") }}
    </PrimaryButton>
    <SecondaryButton class="!w-full" @click="modal = !modal"
      >{{ $t("customize_shipment") }}
    </SecondaryButton>

    <div
      v-if="autoShipmentError"
      class="w-full mt-4 flex gap-2 text-xs bg-red-100 text-red-600 p-3 rounded-md"
    >
      <exclamation-triangle-icon class="w-1/12 h-4" />
      <div class="w-11/12">
        {{ autoShipmentError }}
      </div>
    </div>

    <div class="flex items-start mt-4 text-xs gap-1">
      <information-circle-icon class="w-8" />{{ $t("fast_shipment_desc") }}
    </div>
  </div>

  <div v-else class="bg-red-100 text-red-800 p-2 rounded-md">
    {{ $t("api_key_required") }}
    <a href="/wp-admin/admin.php?page=gcargo-settings" class="underline">{{
      $t("connect")
    }}</a>
  </div>

  <BarcodeModal v-model="pdfUrlModal" :pdf-url="pdfUrl"></BarcodeModal>

  <MdrModal v-model="modal" size="md:size-4/5 lg:size-3/5">
    <template #title>{{ $t("create_shipment") }}</template>

    <div
      v-if="errors.api_error"
      class="w-full flex bg-red-100 border-red-600 rounded-md p-4 break-all text-red-600 items-center gap-2"
    >
      <exclamation-triangle-icon class="w-6 h-6" />
      {{ errors.api_error[0] }}
    </div>

    <div class="grid grid-cols-3 gap-4 divide-x">
      <div
        class="col-span-2 flex flex-col gap-8 overflow-auto max-h-[55vh] min-h-[55vh] pr-1"
      >
        <MdrAccordion>
          <MdrAccordionItem expanded>
            <template #title>
              <div class="font-semibold text-lg text-gray-900">
                {{ $t("receiver_info") }}
              </div>
            </template>
            <div class="flex items-center justify-end mb-4">
              <MdrTooltip>
                <template #trigger>
                  <MdrBadge
                    class="cursor-pointer rounded-full p-1"
                    @click="fix()"
                  >
                    <div class="flex items-center gap-2">
                      <span class="text-xs"> Yapay Zeka İle Düzenle </span>
                      <sparkles-icon class="w-4 h-4" />
                    </div>
                  </MdrBadge>
                </template>
                <template #content>
                  {{ $t("fix_address_desc") }}
                </template>
              </MdrTooltip>
            </div>
            <div class="grid grid-cols-3 gap-4">
              <MdrFormField
                v-for="field in ['name', 'surname', 'phone']"
                :key="field"
                v-model="shipment.customer[field]"
                :label="$t(field)"
                required
                :error="errors[`customer.${field}`]"
              />

              <MdrFormField
                v-model="shipment.customer.email"
                :label="$t('email')"
                required
                :error="errors[`customer.email`]"
              />

              <MdrFormField
                v-model="shipment.customer.postcode"
                :label="$t('postcode')"
                required
                :error="errors['customer.postcode']"
              />

              <CountrySelect v-model="shipment.customer" />

              <div>
                <MdrFormField
                  v-model="shipment.customer.city"
                  :label="cityLabel"
                  required
                  :error="errors[`customer.city`]"
                />
              </div>

              <div v-if="showCityCode">
                <MdrFormField
                  v-model="shipment.customer.city_code"
                  :label="$t('city_code')"
                  required
                  :error="errors[`customer.city_code`]"
                />
              </div>

              <div>
                <MdrFormField
                  v-model="shipment.customer.district"
                  :label="districtLabel"
                  required
                  :error="errors[`customer.district`]"
                />
              </div>

              <MdrFormField
                v-model="shipment.customer.address"
                class="col-span-3"
                :label="$t('address')"
                required
                :error="errors['customer.address']"
              />

              <MdrFormField
                v-if="showCityCode"
                v-model="shipment.description"
                class="col-span-3"
                :label="$t('description')"
              />
            </div>
          </MdrAccordionItem>
        </MdrAccordion>

        <MdrAccordion>
          <MdrAccordionItem>
            <template #title>
              <div class="font-semibold text-lg text-gray-900">
                {{ $t("product_info") }}
              </div>
            </template>

            <div class="flex flex-col gap-4">
              <p>
                {{ $t("product_info_desc") }}
                <a href="https://kargoentegrator.com" target="_blank">{{
                  $t("click_here")
                }}</a
                >.
              </p>

              <div
                v-for="(line, index) in shipment.lines"
                :key="line.platform_id"
                class="flex flex-col border rounded-lg py-2 px-6 gap-2"
              >
                <div class="flex justify-between">
                  <div class="flex items-center gap-4">
                    <div class="border border-gray-200 rounded-lg">
                      <img
                        :src="line.image"
                        alt=""
                        srcset=""
                        class="h-16 w-16 object-cover rounded-lg"
                      />
                    </div>

                    <div class="flex flex-col gap-2">
                      <span class="font-semibold text-xl">
                        {{ line.title }}
                      </span>
                      <span> Sku : {{ line.sku }} </span>
                    </div>
                  </div>

                  <div class="flex items-center gap-4">
                    <div
                      class="flex gap-2 items-center rounded-lg bg-gray-100 px-2"
                    >
                      <span
                        class="font-bold px-1 text-lg cursor-pointer"
                        @click="changeQty(index, -1)"
                        >-</span
                      >
                      <span v-text="shipment.lines[index].quantity" />
                      <span
                        class="font-bold px-1 text-lg cursor-pointer"
                        @click="changeQty(index, +1)"
                        >+</span
                      >
                    </div>
                  </div>
                </div>
                <div class="grid grid-cols-4 gap-4">
                  <MdrFormField
                    v-model="line.price"
                    type="number"
                    :label="$t('line_price')"
                    :error="errors['price']"
                  />
                  <MdrFormField
                    v-model="line.weight"
                    type="number"
                    :label="$t('line_weight')"
                    :error="errors['weight']"
                  />
                </div>
              </div>
            </div>
          </MdrAccordionItem>
        </MdrAccordion>

        <MdrAccordion>
          <MdrAccordionItem>
            <template #title>
              <div class="font-semibold text-lg text-gray-900">
                {{ $t("invoice_info") }}
              </div>
            </template>
            <div class="grid grid-cols-3 gap-4">
              <MdrFormField
                v-for="field in ['invoice_number', 'waybill_number']"
                :key="field"
                v-model="shipment[field]"
                :label="$t(field)"
                required
                :error="errors[`${field}`]"
              />
            </div>
          </MdrAccordionItem>
        </MdrAccordion>
      </div>

      <div class="flex flex-col gap-4 px-4">
        <MdrSelect
          v-if="cargoIntegrations.length > 0"
          v-model="shipment.cargo_integration_id"
          :options="cargoIntegrations"
          value-key="id"
          text-key="name"
          :label="$t('cargo_integration')"
        />

        <a
          v-else
          :href="`${adminUrl}admin.php?page=gcargo-settings`"
          target="_blank"
          class="cursor-pointer flex gap-2 items-center underline text-sm text-red-600 hover:text-red-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          ><exclamation-triangle-icon class="w-8 h-8" />{{
            $t("cargo_integration_warning")
          }}</a
        >
        <MdrSelect
          v-if="warehouses.length > 0"
          v-model="shipment.warehouse_id"
          :options="warehouses"
          value-key="id"
          text-key="name"
          :label="$t('warehouse')"
        />

        <a
          v-else
          :href="`${adminUrl}admin.php?page=gcargo-settings`"
          target="_blank"
          class="cursor-pointer flex gap-2 items-center underline text-sm text-red-600 hover:text-red-700 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          ><exclamation-triangle-icon class="w-8 h-8" />{{
            $t("warehouse_warning")
          }}</a
        >
        <MdrSelect
          v-model="shipment.package_type"
          :options="getShipmentOptions('package_type')"
          value-key="value"
          text-key="text"
          :label="$t('package_type')"
        />

        <MdrFormField
          v-if="showPackageCount"
          v-model="shipment.package_count"
          type="number"
          :label="$t('package_count')"
        />

        <MdrSelect
          v-model="shipment.payor_type"
          :options="getShipmentOptions('payor_type')"
          value-key="value"
          text-key="text"
          :label="$t('payor_type')"
        />

        <MdrSelect
          v-model="shipment.payment_type"
          :options="getShipmentOptions('payment_type')"
          value-key="value"
          text-key="text"
          :label="$t('payment_type')"
        />

        <MdrFormField
          v-model="shipment.desi"
          type="number"
          :label="$t('desi')"
          :error="errors['desi']"
        />

        <MdrFormField
          v-model="shipment.kg"
          type="number"
          :label="$t('weight_kg')"
          :error="errors['kg']"
        />

        <MdrCheckboxField
          v-model="shipment.is_pay_at_door"
          :label="$t('is_pay_at_door')"
        />

        <div v-if="shipment.is_pay_at_door" class="flex gap-2">
          <MdrFormField
            v-model="shipment.total"
            type="number"
            class="w-full"
            :label="$t('total')"
            :disabled="!shipment.is_pay_at_door"
          />
          <MdrSelect
            v-model="shipment.currency"
            class="w-full"
            :disabled="!shipment.is_pay_at_door"
            :options="[
              { value: 'TRY', text: 'TRY' },
              { value: 'EUR', text: 'EUR' },
              { value: 'USD', text: 'USD' },
            ]"
            :label="$t('currency')"
          />
        </div>
      </div>
    </div>
    <template #actions>
      <div class="flex gap-3 justify-end w-full">
        <div class="flex gap-2">
          <DangerButton @click="modal = !modal">{{
            $t("cancel")
          }}</DangerButton>
          <PrimaryButton @click="create()">{{ $t("create") }}</PrimaryButton>
        </div>
      </div>
    </template>
  </MdrModal>
</template>
