<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 MdrModal from "@/components/Mudur-Ui-Kit/MdrModal.vue";
import { onBeforeMount, ref, watch } from "vue";
import { useResourceStore } from "@/stores/ResourceStore";
import MdrFormField from "@/components/Mudur-Ui-Kit/MdrFormField.vue";
import MdrSelect from "@/components/Mudur-Ui-Kit/MdrSelect.vue";
import { successAlert } from "@/components/Mudur-Ui-Kit/alert.js";

const { store } = useResourceStore();
const requests = ref(window.ginvoice.requests);
const result = ref({});
const edit = ref(null);
const modal = ref(false);
const bulkModal = ref(false);

const getCurrentDate = () => new Date().toISOString().slice(0, 10);

const getDefaultIssueDateSource = () => {
  const fromDefaults = window.ginvoice?.defaults?.invoice_date;
  if (["current_date", "order_date", "payment_date"].includes(fromDefaults)) {
    return fromDefaults;
  }

  return "current_date";
};

const defaultIssueDateSource = getDefaultIssueDateSource();
const bulkEdit = ref({
  issue_date_source: defaultIssueDateSource,
  custom_date: "",
  issue_time: "",
});

const getCurrentTime = () => {
  const now = new Date();
  return `${String(now.getHours()).padStart(2, "0")}:${String(
    now.getMinutes(),
  ).padStart(2, "0")}`;
};

const headers = [
  { class: "!w-[3%]", key: "notify", title: "#" },
  { class: "!w-[3%]", key: "order_id", title: "S. No" },
  { class: "!w-[20%]", key: "title", title: "Müşteri Ünvan/Ad-Soyad" },
  { class: "!w-[10%]", key: "tax_number", title: "VKN/TCKN" },
  { class: "!w-[10%]", key: "tax_office", title: "Vergi Dairesi" },
  { class: "!w-[10%]", key: "subtotal", title: "Ara Toplam" },
  { class: "!w-[10%]", key: "tax_total", title: "Vergiler Toplam" },
  { class: "!w-[10%]", key: "discount_total", title: "İndirim Toplam" },
  { class: "!w-[10%]", key: "total", title: "Fatura Toplam" },
  { class: "!w-[10%]", key: "issue_date", title: "Düz. Tarihi" },
  { class: "!w-[4%]", key: "actions", title: "" },
];

onBeforeMount(() => {
  for (const request of requests.value) {
    result.value[request.order_id] = {
      creating: false,
      created: false,
      error: false,
    };
  }
});

const create = async () => {
  for (const request of requests.value) {
    if (result.value[request.order_id].created) continue;
    result.value[request.order_id].creating = true;
    try {
      await store({
        data: {
          resource: "invoice",
          data: request,
        },
        beforeSend: () => {},
      });
      result.value[request.order_id].created = true;
    } catch (error) {
      result.value[request.order_id].error = true;
    }
    result.value[request.order_id].creating = false;
  }

  successAlert({
    message:
      "Oluşturma işlem tamamlandı, faturaların aktarım durumlarını sipariş detayından takip edebilirsiniz. Hatalı faturaları 'Kalem' işareti ile düzenleyip tekrar deneyebilirsiniz.'",
  });
};

const getSubtotal = (item) => {
  return item.lines.reduce((acc, line) => {
    return acc + line.quantity * line.unit_price;
  }, 0);
};

const getTaxTotal = (item) => {
  return item.lines.reduce((acc, line) => {
    return acc + (line.quantity * line.unit_price * line.tax_rate) / 100;
  }, 0);
};

const getDiscountTotal = (item) => {
  return item.lines.reduce((acc, line) => {
    return acc + line.discount;
  }, 0);
};

const getTotal = (item) => {
  const subTotal = getSubtotal(item);
  return subTotal - getDiscountTotal(item) + getTaxTotal(item);
};

const openEditModal = (item) => {
  edit.value = item;
  modal.value = true;
};

const openBulkEditModal = () => {
  bulkEdit.value = {
    issue_date_source: defaultIssueDateSource,
    custom_date: "",
    issue_time: "",
  };
  syncBulkEditPreview();
  bulkModal.value = true;
};

const syncBulkEditPreview = () => {
  const firstRequest = requests.value?.[0];
  const selectedDate = resolveIssueDate(firstRequest);

  if (bulkEdit.value.issue_date_source === "custom_date") {
    bulkEdit.value.custom_date = getCurrentDate();
    bulkEdit.value.issue_time = getCurrentTime();
    return;
  }

  bulkEdit.value.custom_date = selectedDate || "";
  bulkEdit.value.issue_time = firstRequest?.issue_time || "";
};

const resolveIssueDate = (request) => {
  if (!request && bulkEdit.value.issue_date_source !== "custom_date") {
    return getCurrentDate();
  }

  switch (bulkEdit.value.issue_date_source) {
    case "order_date":
      return request.order_created_at || request.issue_date;
    case "payment_date":
      return request.payment_date || request.issue_date;
    case "custom_date":
      return bulkEdit.value.custom_date || request.issue_date;
    case "current_date":
    default:
      return getCurrentDate();
  }
};

const applyBulkEditDate = () => {
  for (const request of requests.value) {
    request.issue_date = resolveIssueDate(request);
    if (bulkEdit.value.issue_time) {
      request.issue_time = bulkEdit.value.issue_time;
    }
  }
  bulkModal.value = false;
};

watch(
  () => bulkEdit.value.issue_date_source,
  () => {
    syncBulkEditPreview();
  },
);
</script>
<template>
  <Page>
    <div class="flex justify-between pb-4">
      <h3 class="text-xl font-semibold text-primary-600">
        Toplu Fatura Oluştur
      </h3>
      <div class="flex gap-2">
        <MdrModal
          v-model="bulkModal"
          dense
          size="!max-w-2xl !w-full"
          @close="bulkModal = false"
        >
          <template #title>Toplu Düzenleme Tarihi</template>
          <div class="grid gap-2">
            <MdrSelect
              v-model="bulkEdit.issue_date_source"
              class="col-span-2"
              dense
              label="Fatura Tarihi"
              :options="[
                { value: 'current_date', text: 'Güncel Tarih' },
                { value: 'order_date', text: 'Sipariş Tarihi' },
                { value: 'payment_date', text: 'Ödeme Tarihi' },
                { value: 'custom_date', text: 'Özel Tarih' },
              ]"
            />
            <div class="flex flex-col col-span-2 gap-2">
              <MdrFormField
                v-if="bulkEdit.issue_date_source === 'custom_date'"
                v-model="bulkEdit.custom_date"
                dense
                label="Düzenleme Tarihi"
                type="date"
                class="col-span-2"
              />
              <MdrFormField
                v-if="bulkEdit.issue_date_source === 'custom_date'"
                v-model="bulkEdit.issue_time"
                dense
                label="Düzenleme Saati"
                type="time"
                class="col-span-2"
              />
            </div>
          </div>
          <template #actions>
            <PrimaryButton @click="applyBulkEditDate">
              Tüm Faturalara Uygula
            </PrimaryButton>
          </template>
        </MdrModal>
        <SecondaryButton @click="openBulkEditModal"
          ><archive-box-icon class="size-4 mr-2" /> Düzenleme Tarihini
          Güncelle</SecondaryButton
        >
        <PrimaryButton
          :disabled="Object.values(result).some((item) => item.creating)"
          @click="create"
          >Oluştur
        </PrimaryButton>
      </div>
    </div>
    <MdrTable
      :items="requests"
      :headers="headers"
      no-data-text="Fatura oluşturulacak sipariş bulunamadı. Siparişleriniz faturalandırılmış olabilir yada faturalandırmaya uygun olmayabilir."
    >
      <template #notify="{ item }">
        <div class="w-full items-center justify-center p-1">
          <div v-if="result[item.order_id].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[item.order_id].created"
            class="size-5 text-green-600"
          />
          <exclamation-triangle-icon
            v-else-if="result[item.order_id].error"
            class="size-5 text-red-600"
          />
          <span v-else>-</span>
        </div>
      </template>

      <template #title="{ item }">
        {{
          item.customer.type === "company"
            ? item.customer.title
            : item.customer.name + " " + item.customer.surname
        }}
      </template>

      <template #tax_number="{ item }">
        {{ item.customer.tax_number }}
      </template>

      <template #tax_office="{ item }">
        {{ item.customer.tax_office }}
      </template>

      <template #subtotal="{ item }">
        <money-format :currency="item.currency" :money="getSubtotal(item)" />
      </template>

      <template #tax_total="{ item }">
        <money-format :currency="item.currency" :money="getTaxTotal(item)" />
      </template>

      <template #discount_total="{ item }">
        <money-format
          :currency="item.currency"
          :money="getDiscountTotal(item)"
        />
      </template>

      <template #total="{ item }">
        <money-format
          :currency="item.currency"
          class="font-bold"
          :money="getTotal(item)"
        />
      </template>

      <template #issue_date="{ item }">
        {{ item.issue_date }}
      </template>

      <template #actions="{ item }">
        <pencil-icon
          class="size-3 text-primary-600 cursor-pointer"
          @click="openEditModal(item)"
        />
      </template>
    </MdrTable>
    <MdrModal v-model="modal" dense @close="modal = false">
      <template #title>Fatura Düzenle</template>
      <div class="grid grid-cols-4 gap-2">
        <MdrSelect
          v-model="edit.customer.type"
          dense
          label="Müşteri Tipi"
          class="col-span-2"
          :options="[
            { value: 'company', text: 'Tüzel Kişi' },
            { value: 'person', text: 'Gerçek Kişi' },
          ]"
        />
        <MdrFormField
          v-model="edit.customer.tax_number"
          dense
          label="VKN/TCKN"
        />
        <MdrFormField
          v-model="edit.customer.tax_office"
          dense
          label="Vergi Dairesi"
        />

        <template v-if="edit.customer.type === 'person'">
          <MdrFormField v-model="edit.customer.name" dense label="Ad" />
          <MdrFormField v-model="edit.customer.surname" dense label="Soyad" />
        </template>
        <MdrFormField
          v-else
          v-model="edit.customer.title"
          dense
          label="Ünvan"
          class="col-span-2"
        />
        <MdrFormField
          v-model="edit.customer.address"
          dense
          label="Adres"
          class="col-span-2"
        />

        <MdrFormField v-model="edit.customer.district" dense label="İlçe" />
        <MdrFormField v-model="edit.customer.city" dense label="İl" />
        <MdrFormField v-model="edit.customer.phone" dense label="Telefon" />
        <MdrFormField v-model="edit.customer.email" dense label="Email" />
        <MdrFormField
          v-model="edit.issue_date"
          dense
          label="Düzenleme Tarihi"
          type="date"
          class="col-span-2"
        />
        <MdrFormField
          v-model="edit.issue_time"
          dense
          label="Düzenleme Saati"
          type="time"
          class="col-span-2"
        />
      </div>
      <template #actions>
        <PrimaryButton @click="modal = false"> Tamam </PrimaryButton>
      </template>
    </MdrModal>
  </Page>
</template>
