<script setup>
import { computed, ref } from "vue";
import MdrModal from "./Mudur-Ui-Kit/MdrModal.vue";
import MdrAccordion from "./Mudur-Ui-Kit/MdrAccordion.vue";
import MdrAccordionItem from "./Mudur-Ui-Kit/MdrAccordionItem.vue";
import MdrFormField from "./Mudur-Ui-Kit/MdrFormField.vue";
import MdrCheckboxField from "./Mudur-Ui-Kit/MdrCheckboxField.vue";
import PrimaryButton from "./Buttons/PrimaryButton.vue";
import SecondaryButton from "./Buttons/SecondaryButton.vue";
import MdrSelect from "./Mudur-Ui-Kit/MdrSelect.vue";
import BarcodeModal from "@/components/BarcodeModal.vue";
import DangerButton from "./Buttons/DangerButton.vue";

import { useResourceStore } from "@/stores/ResourceStore";
import { shipmentSettingFields } from "@/utils/fields";
import { useI18n } from "vue-i18n";
import { successAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { useApiRequestStore } from "@/stores/ApiRequestStore";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({}),
  },
});
const { cargoIntegrations, warehouses } = useResourceStore();
const emit = defineEmits(["update:modelValue"]);
const returned = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

const { store } = useResourceStore();
const errors = ref({});
const { getPdf } = useApiRequestStore();
const pdfUrlModal = ref(false);
const pdfUrl = ref();
const { t } = useI18n();

const createReturned = async () => {
  errors.value = {};
  returned.value.lines = returned.value.lines.filter((line) => line.selected);

  if (returned.value.lines.length === 0) {
    errors.value.lines = t("select_returned_item");
    return;
  }

  const response = await store({
    data: {
      resource: "returneds",
      data: returned.value,
    },
    onValidationError: (response) => {
      errors.value = response.errors;
    },
  });
  modal.value = false;
  successAlert({ message: t("resource_added", [t("returned")]) });
  pdfUrl.value = await getPdf({
    data: { returneds: [response.id] },
    type: "returned",
  });
  pdfUrlModal.value = true;
};

const modal = ref(false);

const changeQty = (item, value) => {
  let newQuantity = item.quantity + value;

  if (newQuantity < 0) {
    newQuantity = 0;
  }

  if (newQuantity > item.sold_qty) {
    newQuantity = item.sold_qty;
  }

  item.quantity = newQuantity;
};
</script>

<template>
  <BarcodeModal v-model="pdfUrlModal" :pdf-url="pdfUrl"></BarcodeModal>
  <div class="pt-2">
    <SecondaryButton class="!w-full" @click="modal = true">
      {{ $t("create_returned") }}
    </SecondaryButton>
  </div>
  <MdrModal v-model="modal" size="md:size-4/5 lg:size-3/5">
    <template #title>
      <div class="font-semibold text-lg text-gray-900">
        {{ $t("product_info") }}
      </div>
    </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
      v-if="errors.lines"
      class="w-full flex bg-red-100 border-red-600 rounded-md p-4 text-red-600 items-center gap-2 mt-2"
    >
      <exclamation-triangle-icon class="w-6 h-6" />
      {{ errors.lines }}
    </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="grid grid-cols-3 gap-4">
              <MdrFormField
                v-for="field in [
                  'name',
                  'surname',
                  'phone',
                  'email',
                  'city',
                  'district',
                  'postcode',
                  'country',
                  'address',
                ]"
                :key="field"
                v-model="returned.customer[field]"
                :class="field === 'address' ? 'col-span-3' : ''"
                :label="$t(field)"
                required
                :error="errors[`customer.${field}`]"
              />
            </div>
          </MdrAccordionItem>
        </MdrAccordion>
        <MdrAccordion>
          <MdrAccordionItem expanded>
            <template #title>
              <div class="font-semibold text-lg text-gray-900">
                {{ $t("product_info") }}
              </div>
            </template>
            <div
              v-for="item in returned.lines"
              :key="item.platform_id"
              class="px-4 py-2 border border-gray-200 rounded-lg"
            >
              <div class="flex items-center gap-4">
                <MdrCheckboxField
                  v-model="item.selected"
                  :value="item.platform_id"
                />
                <img
                  :src="item.image"
                  class="object-cover size-16 rounded-lg"
                />
                <div class="flex justify-between items-center w-full">
                  <span class="font-semibold text-md">{{ item.title }}</span>
                  <span v-if="item.sku">Sku : {{ item.sku }}</span>
                  <div class="flex">
                    <div class="flex items-center">
                      <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(item, -1)"
                          >-</span
                        >
                        <span v-text="item.quantity" />
                        <span
                          class="font-bold px-1 text-lg cursor-pointer"
                          @click="changeQty(item, 1)"
                          >+</span
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="py-2 mt-4 border-t border-gray-200">
                <MdrFormField
                  v-model="item.reason"
                  :label="$t('return_reason')"
                />
              </div>
            </div>
            <div class="mt-4">
              <label class="block text-sm font-medium text-gray-700"
                >{{ $t("return_date") }}
                <span class="text-red-600">*</span>
              </label>
              <input
                v-model="returned.return_at"
                type="date"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                required
              />
            </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="returned[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="returned.cargo_integration_id"
          :options="cargoIntegrations"
          value-key="id"
          text-key="name"
          :label="$t('cargo_integration')"
        />

        <a
          v-else
          href="https://staging.kargoentegrator.com/integration/cargo"
          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="returned.warehouse_id"
          :options="warehouses"
          value-key="id"
          text-key="name"
          :label="$t('warehouse')"
        />

        <a
          v-else
          href="https://app.kargoentegrator.com/warehouse"
          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-for="set in shipmentSettingFields(t)"
          :key="set.model"
          v-model="returned[`${set.model}`]"
          :label="set.label"
          :options="set.options"
          value-key="value"
          text-key="text"
        />
      </div>
    </div>
    <template #actions>
      <DangerButton @click="modal = false">{{ $t("cancel") }}</DangerButton>
      <PrimaryButton @click="createReturned">{{ $t("create") }}</PrimaryButton>
    </template>
  </MdrModal>
</template>
