<script setup>
import SettingsTab from "@/layouts/SettingsTab.vue";
import MdrBadge from "@/components/Mudur-Ui-Kit/MdrBadge.vue";
import MdrTable from "@/components/Mudur-Ui-Kit/MdrTable.vue";
import MdrModal from "@/components/Mudur-Ui-Kit/MdrModal.vue";
import MdrFormField from "@/components/Mudur-Ui-Kit/MdrFormField.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import DangerButton from "@/components/Buttons/DangerButton.vue";
import { useResourceStore } from "@/stores/ResourceStore";
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import { successAlert, confirmAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { warehouses } = storeToRefs(useResourceStore());
const { store, index, update, destroy } = useResourceStore();
const defaultWarehouse = {
  id: "",
  name: "",
  person_name: "",
  person_surname: "",
  person_tckn: "",
  phone: "",
  email: "",
  city: "",
  district: "",
  neighborhood: "",
  address: "",
  is_default: true,
};
const modal = ref(false);
const errors = ref({});
const warehouse = ref(defaultWarehouse);
const search = ref("");

const normalizeSearchValue = (value) =>
  String(value ?? "")
    .toLocaleLowerCase("tr-TR")
    .trim();

const filteredWarehouses = computed(() => {
  const query = normalizeSearchValue(search.value);

  if (!query) {
    return warehouses.value;
  }

  return (warehouses.value ?? []).filter((warehouse) =>
    [
      warehouse.name,
      warehouse.address,
      warehouse.district,
      warehouse.city,
      warehouse.person_name,
      warehouse.person_surname,
      warehouse.phone,
      warehouse.email,
    ]
      .map(normalizeSearchValue)
      .some((value) => value.includes(query)),
  );
});

const openModal = async (item) => {
  warehouse.value = item ? item : defaultWarehouse;
  modal.value = true;
};
const reIndex = async () => {
  warehouses.value = await index({
    data: {
      resource: "warehouses",
    },
  });
  modal.value = false;
};
const patch = async () => {
  await update({
    data: {
      resource: "warehouses",
      data: warehouse.value,
      id: warehouse.value.id,
    },
    onValidationError: (response) => {
      errors.value = response.errors;
    },
  });
  await reIndex();
  successAlert({ title: t("resource_updated", [t("warehouse")]) });
};

const add = async () => {
  await store({
    data: {
      resource: "warehouses",
      data: warehouse.value,
    },
    onValidationError: (response) => {
      errors.value = response.errors;
    },
  });
  await reIndex();
  successAlert({ title: t("resource_created", [t("warehouse")]) });
};

const del = () => {
  confirmAlert({
    title: t("cancel_title"),
    message: t("resource_delete", [t("warehouse")]),
    onConfirm: async () => {
      await destroy({
        data: {
          resource: "warehouses",
          id: warehouse.value.id,
        },
      });
      await reIndex();
      successAlert({ title: t("resource_deleted", [t("warehouse")]) });
    },
  });
};

const setDefault = async () => {
  await update({
    data: {
      resource: "warehouses",
      data: {
        is_default: true,
      },
      id: warehouse.value.id,
    },
  });
  await reIndex();
  successAlert({ title: t("resource_updated", [t("warehouse")]) });
};
</script>
<template>
  <SettingsTab>
    <template #title>
      <div class="flex justify-between items-end">
        {{ $t("warehouses") }}

        <PrimaryButton @click="openModal()">{{ $t("add") }} </PrimaryButton>
      </div>
    </template>
    <template #description>
      {{ $t("warehouses_top", ["Kargo Entegratör"]) }}
    </template>

    <div class="mb-4">
      <input
        v-model="search"
        type="text"
        class="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-primary-500 focus:ring-primary-500"
        :placeholder="`${$t('warehouse')} ara...`"
      />
    </div>

    <MdrTable
      :items="filteredWarehouses"
      :not-found-text="$t('record_not_found', [$t('warehouse')])"
      :headers="[
        { title: $t('warehouse_name'), key: 'name' },
        { title: $t('address'), key: 'address' },
        { title: `${$t('district')}/${$t('city')}`, key: 'city' },
        { title: $t('created_at'), key: 'created_at' },
      ]"
      @tr-clicked="openModal"
    >
      <template #name="{ item }">
        <div class="flex gap-2 items-center">
          <span>{{ item.name }} </span>
          <MdrBadge
            v-if="item.is_default"
            class="!bg-green-200 !text-green-600"
            >{{ $t("default") }}</MdrBadge
          >
        </div>
      </template>
      <template #city="{ item }">
        {{ `${item.district}/${item.city}` }}
      </template>
      <template #created_at="{ item }">
        <time-format :date="item.created_at" />
      </template>
    </MdrTable>
    <MdrModal v-model="modal">
      <template #title>{{
        warehouse.id
          ? $t("resource_update", [$t("warehouse")])
          : $t("resource_add", [$t("warehouse")])
      }}</template>
      <div class="grid grid-cols-2 gap-4">
        <MdrFormField
          v-for="field in [
            'name',
            'person_name',
            'person_surname',
            'person_tckn',
            'phone',
            'email',
            'city',
            'district',
            'neighborhood',
            'address',
          ]"
          :key="field"
          v-model="warehouse[field]"
          :class="field === 'name' || field === 'address' ? 'col-span-2' : ''"
          :label="$t(field)"
          :error="errors[field]"
          required
          auto-complete=""
          type="text"
          :placeholder="`${$t(field)} giriniz...`"
        />
      </div>
      <template #actions>
        <div class="flex justify-between items-end w-full">
          <div class="flex gap-2">
            <template v-if="!warehouse.is_default && warehouse.id">
              <span
                class="underline text-xs cursor-pointer flex items-end"
                @click="del"
              >
                <trash-icon class="w-4" />
                {{ $t("delete") }}</span
              >

              <span
                class="underline text-xs text-primary-600 cursor-pointer flex items-end"
                @click="setDefault"
              >
                <check-badge-icon class="w-4" />
                {{ $t("set_default") }}</span
              >
            </template>
          </div>
          <div class="flex gap-2">
            <DangerButton @click="modal = !modal">{{
              $t("cancel")
            }}</DangerButton>
            <PrimaryButton @click="warehouse.id ? patch() : add()">{{
              warehouse.id ? $t("update") : $t("add")
            }}</PrimaryButton>
          </div>
        </div>
      </template>
    </MdrModal>
  </SettingsTab>
</template>
