<script setup>
import Page from "@/layouts/Page.vue";
import MdrTable from "@/components/Mudur-Ui-Kit/MdrTable.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import SecondaryButton from "@/components/Buttons/SecondaryButton.vue";
import { onBeforeMount, ref, onMounted, onUnmounted } from "vue";
import { useResourceStore } from "@/stores/ResourceStore";
import { useApiRequestStore } from "@/stores/ApiRequestStore.js";
import { errorAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const { store } = useResourceStore();
const { fixAddress } = useApiRequestStore();
const orders = ref(window.gcargo.orders);
const creating = ref(false);
const edit = ref([]);
const result = ref([]);
const showPopover = ref([]);
const headers = [
  { class: "!w-[3%]", key: "notify", title: "#" },
  { class: "!w-[5%]", key: "platform_id", title: "S. No" },
  { class: "!w-[13%]", key: "name", title: t("name") },
  { class: "!w-[13%]", key: "surname", title: t("surname") },
  { class: "!w-[12%]", key: "phone", title: t("phone") },
  { class: "!w-[12%]", key: "city", title: t("city") },
  { class: "!w-[12%]", key: "district", title: t("district") },
  { class: "!w-[30%]", key: "address", title: t("address") },
];

const addressFields = ['city', 'district', 'address'];

const createBulkShipment = async () => {
  creating.value = true;
  let index = 0;
  for (const order of orders.value) {
    if (!result.value[index].created) {
      result.value[index].creating = true;
      try {
        const response = await store({
          data: {
            resource: "shipments",
            data: order,
          },
          onValidationError: () => {},
          beforeSend: () => {},
        });
        orders.value[index].current_shipments.push(response.id);
        result.value[index] = { creating: false, created: true };
      } catch (error) {
        result.value[index].creating = false;
        result.value[index].error = true;
        errorAlert({
          message: `${order.platform_id} : ${error.responseJSON.message}`,
        });
      }
    }
    index++;
  }
  creating.value = false;
};

const getLink = () => {
  let queryArray = [];

  orders.value.forEach((order) => {
    queryArray.push(order.current_shipments.map((id) => `print-data[]=${id}`));
  });
  return `${window.gcargo.admin_url}admin.php?page=gcargo-bulk-print&${queryArray.join("&")}`;
};

const openAddressEdit = (index) => {
  const filteredHeaders = headers.filter(
    (header) => !['notify', 'platform_id'].includes(header.key)
  );
  
  filteredHeaders.forEach((header, headerIndex) => {
    if (addressFields.includes(header.key)) {
      edit.value[index][headerIndex] = true;
    }
  });
};

const fixCustomerAddress = async (index, key) => {
  const customer = orders.value[index].customer;
  const addressData = {
    address: customer.address,
    district: customer.district,
    city: customer.city,
    country: customer.country || 'Türkiye'
  };
  
  const response = await fixAddress({ data: addressData });
  if (response) {
    orders.value[index].customer = {
      ...orders.value[index].customer,
      city: response.formattedAddress.city || customer.city,
      district: response.formattedAddress.district || customer.district,
      address: response.formattedAddress.fullAddress || customer.address,
      country: response.formattedAddress.country || customer.country,
    };
  }
  showPopover.value[index][key] = false;
};

const togglePopover = (index, key) => {
  showPopover.value.forEach((row, rowIndex) => {
    if (rowIndex !== index) {
      Object.keys(row).forEach(k => {
        row[k] = false;
      });
    } else {
      Object.keys(row).forEach(k => {
        if (k !== key.toString()) {
          row[k] = false;
        }
      });
    }
  });
  
  showPopover.value[index][key] = !showPopover.value[index][key];
};

const closeAllPopovers = () => {
  showPopover.value.forEach(row => {
    Object.keys(row).forEach(key => {
      row[key] = false;
    });
  });
};

const handleClickOutside = (event) => {
  if (!event.target.closest('.popover-container')) {
    closeAllPopovers();
  }
};

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

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});

onBeforeMount(() => {
  for (let i = 0; i <= orders.value.length - 1; i++) {
    result.value.push({
      creating: false,
      created: !orders.value[i].need_shipment,
      error: false,
    });
    const editProp = {};
    const popoverProp = {};
    for (let j = 0; j <= headers.length; j++) {
      editProp[j] = false;
      popoverProp[j] = false;
    }
    edit.value.push(editProp);
    showPopover.value.push(popoverProp);
  }
});
</script>
<template>
  <Page>
    <div class="flex justify-between pb-4">
      <h3 class="text-xl font-semibold text-primary-600">
        {{ $t("create_bulk_shipment") }}
      </h3>
      <div class="flex gap-2">
        <SecondaryButton
          :disabled="!result.find((e) => e.created)"
          :link="getLink()"
          target="_blank"
          >{{ $t("print") }}
        </SecondaryButton>
        <PrimaryButton :disabled="creating" @click="createBulkShipment"
          >{{ $t("create_shipment") }}
        </PrimaryButton>
      </div>
    </div>
    <MdrTable :items="orders" :headers="headers">
      <template #notify="{ index }">
        <div class="w-full items-center justify-center p-1">
          <div v-if="result[index].creating" role="status">
            <svg
              aria-hidden="true"
              class="inline size-5 text-gray-200 animate-spin dark:text-gray-600 fill-primary-600"
              viewBox="0 0 100 101"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                fill="currentColor"
              />
              <path
                d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                fill="currentFill"
              />
            </svg>
            <span class="sr-only">Loading...</span>
          </div>
          <check-circle-icon
            v-else-if="result[index].created"
            class="size-5 text-green-600"
          />
          <exclamation-triangle-icon
            v-else-if="result[index].error"
            class="size-5 text-red-600"
          />
          <span v-else>-</span>
        </div>
      </template>

      <template
        v-for="(header, key) in headers.filter(
          (header) => !['notify', 'platform_id'].includes(header.key),
        )"
        #[header.key]="{ item, index }"
        :key="key"
      >
        <div v-if="addressFields.includes(header.key)" class="relative">
          <div
            v-if="!edit[index][key]"
            class="w-full flex justify-between items-center group cursor-text"
          >
            <span>
              {{ item.customer[header.key] }}
            </span>

            <div class="flex items-center gap-1">
              <div class="relative">
                <button
                  class="size-3 text-primary-600 opacity-0 group-hover:opacity-100 transition-opacity"
                  @click.stop="togglePopover(index, key)"
                >
                  <pencil-icon />
                </button>
                
                <div
                  v-if="showPopover[index][key]"
                  class="popover-container absolute right-0 top-full mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 py-1 z-10"
                  @click.stop
                >
                  <button
                    class="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 flex items-center gap-2"
                    @click="openAddressEdit(index, key)"
                  >
                    <pencil-icon class="size-4" />
                    {{ $t("edit") }}
                  </button>
                  <button
                    class="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 flex items-center gap-2"
                    @click="fixCustomerAddress(index, key)"
                  >
                    <sparkles-icon class="size-4" />
                    {{ $t("fix_address_desc") }}
                  </button>
                </div>
              </div>
            </div>
          </div>

          <input
            v-else
            v-model="orders[index].customer[header.key]"
            type="text"
            autofocus
            class="!text-xs w-full"
            @keyup.enter="edit[index][key] = false"
            @blur="edit[index][key] = false"
          />
        </div>

        <div v-else>
          <div
            v-if="!edit[index][key]"
            class="w-full flex justify-between items-center group cursor-text"
            
          >
            <span>
              {{ item.customer[header.key] }}
            </span>

            <pencil-icon
              @click="edit[index][key] = true"
              class="size-3 text-primary-600 opacity-0 group-hover:opacity-100 transition-opacity"
            />
          </div>

          <input
            v-else
            v-model="orders[index].customer[header.key]"
            type="text"
            autofocus
            class="!text-xs w-full"
            @keyup.enter="edit[index][key] = false"
            @blur="edit[index][key] = false"
          />
        </div>
      </template>
    </MdrTable>
  </Page>
</template>
