<script setup>
import MdrModal from "@/components/Mudur-Ui-Kit/MdrModal.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import { useUiStore } from "@/stores/UiStore";
import { ref, computed } from "vue";
import { storeToRefs } from "pinia";
import { useResourceStore } from "@/stores/ResourceStore";
const { cargoIntegration, cargoIntegrations } = storeToRefs(useResourceStore());
const { store, index } = useResourceStore();
const { cargoCompanies } = useUiStore();
const search = ref("");
const modal = ref(false);
const emit = defineEmits(["integration-added"]);

const filteredCompanies = computed(() => {
  return cargoCompanies.filter((e) =>
    e.title.toLowerCase().includes(search.value.toLowerCase()),
  );
});

const createCargoIntegration = async (company) => {
  cargoIntegration.value = await store({
    data: {
      resource: "cargo_integrations",
      data: {
        id: company.id,
      },
    },
  });
  cargoIntegrations.value = await index({
    data: {
      resource: "cargo_integrations",
    },
  });
  modal.value = false;
  emit("integration-added");
};
</script>
<template>
  <PrimaryButton @click="modal = !modal">{{ $t("add") }} </PrimaryButton>
  <MdrModal v-model="modal" size="max-w-xl">
    <template #title>{{
      $t("resource_add", [$t("cargo_integration")])
    }}</template>
    <div class="flex flex-col gap-3">
      <div
        class="flex items-center border border-gray-300 rounded-lg px-3 py-1 hover:shadow-inner"
      >
        <magnifying-glass-icon class="w-4 h-4 text-gray-400" />
        <input
          v-model="search"
          type="text"
          placeholder="Arama"
          class="!border-none !ring-0 w-full"
        />
      </div>
      <div class="h-96 overflow-y-auto flex flex-col gap-4 pr-2">
        <div
          v-for="company in filteredCompanies"
          :key="company.id"
          class="bg-white px-6 py-3 min-h-20 flex justify-between items-center rounded-lg border border-gray-200 hover:shadow gap-3 text-sm cursor-pointer"
        >
          <div class="flex gap-2 items-center">
            <img
              :src="company.logo"
              class="max-w-12 object-contain rounded-lg"
            />
            <span class="font-semibold text-gray-900">{{ company.title }}</span>
          </div>

          <PrimaryButton
            v-if="company.enabled"
            @click="createCargoIntegration(company)"
            >Ekle</PrimaryButton
          >

          <lock-closed-icon v-else class="w-6 h-6 text-primary-800" />
        </div>
      </div>
    </div>
  </MdrModal>
</template>
