<script setup>
import { computed, ref } from "vue";
import MdrTable from "@/components/Mudur-Ui-Kit/MdrTable.vue";
import MarketplaceForm from "./Marketplace/MarketplaceForm.vue";

const selectedSellerId = ref(null);
const search = ref("");

const sellers = window.gcargo.sellers;

const headers = [
  {
    title: "#",
    key: "ID",
    class: "text-xs",
  },
  {
    title: "Kullanıcı Adı",
    key: "user_login",
    class: "text-xs",
  },
  {
    title: "E-posta",
    key: "user_email",
    class: "text-xs",
  },
  {
    title: "Mağaza Adı",
    key: "store_name",
    class: "text-xs",
  },
  {
    title: "Adres",
    key: "address",
    class: "text-xs",
  },
  {
    title: "İl/İlçe",
    key: "location",
    class: "text-xs",
  },
  {
    title: "Telefon",
    key: "phone",
    class: "text-xs",
  },
  {
    title: "Durum",
    key: "seller_id",
    class: "text-xs",
  },
];

const processedSellers =
  sellers?.users?.map((seller) => ({
    ...seller,
    seller_id: seller.data.gcargo_seller_id,
    user_login: seller.data.user_login,
    user_email: seller.data.user_email,
    store_name: seller.data.store_info.store_name,
    phone: seller.data.store_info.phone,
    address: seller.data.address.street_1,
    location: seller.data.address.state + " / " + seller.data.address.city,
  })) ?? [];

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

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

  if (!query) {
    return processedSellers;
  }

  return processedSellers.filter((seller) =>
    [
      seller.ID,
      seller.user_login,
      seller.user_email,
      seller.store_name,
      seller.address,
      seller.location,
      seller.phone,
      seller.seller_id ? "kayıt edildi" : "",
    ]
      .map(normalizeSearchValue)
      .some((value) => value.includes(query)),
  );
});

const handleTrClick = (item) => {
  if (item.seller_id) {
    return;
  }

  selectedSellerId.value = item.ID;
};

const handleFormClose = () => {
  selectedSellerId.value = null;
};
</script>

<template>
  <div>
    <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="Satıcı ara..."
      />
    </div>

    <MdrTable
      :items="filteredSellers"
      :headers="headers"
      @tr-clicked="handleTrClick"
    >
      <template #seller_id="{ item }">
        <span v-if="item.seller_id">Kayıt Edildi</span>
        <span v-else>-</span>
      </template>
    </MdrTable>

    <MarketplaceForm
      v-if="selectedSellerId"
      :key="selectedSellerId"
      :seller-id="selectedSellerId"
      @close="handleFormClose"
    />
  </div>
</template>
