<script setup>
import { ref, onMounted, watch } from "vue";
import MdrFormField from "@/components/Mudur-Ui-Kit/MdrFormField.vue";
import MdrModal from "@/components/Mudur-Ui-Kit/MdrModal.vue";
import { successAlert, errorAlert } from "@/components/Mudur-Ui-Kit/alert.js";
import SecondaryButton from "@/components/Buttons/SecondaryButton.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";
import { useApiRequestStore } from "@/stores/ApiRequestStore.js";

const props = defineProps({
  sellerId: {
    type: [String, Number],
    default: null,
  },
});

const { createMpSeller } = useApiRequestStore();
const errors = ref({});
const isOpen = ref(true);
const emit = defineEmits(["close"]);

const fields = [
  {
    model: "company",
    label: "Firma/Kişi",
    class: "col-span-2",
    autoComplete: "",
    required: true,
  },
  {
    model: "name",
    label: "Yetkili Ad",
    class: "",
    autoComplete: "",
    required: true,
  },
  {
    model: "surname",
    label: "Yetkili Soyad",
    class: "",
    autoComplete: "",
    required: true,
  },
  {
    model: "phone",
    label: "Telefon",
    class: "",
    autoComplete: "",
    required: true,
  },
  {
    model: "email",
    label: "E-Posta",
    class: "",
    autoComplete: "",
    required: true,
  },
  { model: "city", label: "İl", class: "", autoComplete: "", required: true },
  {
    model: "district",
    label: "İlçe",
    class: "",
    autoComplete: "",
    required: true,
  },
  {
    model: "neighborhood",
    label: "Mahalle",
    class: "col-span-2",
    autoComplete: "",
    required: true,
  },
  {
    model: "address",
    label: "Adres",
    class: "col-span-2",
    autoComplete: "",
    required: true,
  },
];

const formData = ref({
  company: "",
  name: "",
  surname: "",
  phone: "",
  email: "",
  city: "",
  district: "",
  neighborhood: "",
  address: "",
  platform_seller_id: props.sellerId,
});

watch(
  () => props.sellerId,
  (newSellerId) => {
    if (newSellerId) {
      formData.value.platform_seller_id = newSellerId;
      loadSellerData();
    }
  },
);

onMounted(() => {
  if (props.sellerId) {
    loadSellerData();
  }
});

const save = async () => {
  const response = await createMpSeller({
    data: formData.value,
  });

  if (response.response.code === 201) {
    successAlert({ message: "Satıcı ve depo başarıyla kaydedildi!" });
    window.location.reload();
  } else {
    const parsedData = JSON.parse(response.body);
    errors.value = parsedData.errors || {};
    errorAlert({ message: parsedData.message });
  }
};

const closeModal = () => {
  isOpen.value = false;
  emit("close");
};

const loadSellerData = () => {
  if (!props.sellerId) {
    return;
  }

  const sellers = window.gcargo.sellers;
  const seller = sellers.users.find((s) => s.ID == props.sellerId);

  formData.value.company = seller.data.store_info.store_name;
  formData.value.name = seller.data.name;
  formData.value.surname = seller.data.surname;
  formData.value.phone = seller.data.store_info.phone;
  formData.value.email = seller.data.user_email;
  formData.value.city = seller.data.address.state;
  formData.value.district = seller.data.address.city;
  formData.value.neighborhood = seller.data.address.street_1;
  formData.value.address = seller.data.address.street_2;
};
</script>

<template>
  <MdrModal v-model="isOpen" size="max-w-4xl" @on-hide="closeModal">
    <template #title> Satıcı Detayları </template>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <template v-for="field in fields" :key="field.model">
        <div :class="field.class">
          <MdrFormField
            v-model="formData[field.model]"
            :label="field.label"
            :required="field.required"
            :auto-complete="field.autoComplete"
            type="text"
            :placeholder="`${field.label} giriniz...`"
            :error="errors[field.model]"
          />
        </div>
      </template>
    </div>

    <template #actions>
      <SecondaryButton @click="closeModal"> İptal </SecondaryButton>
      <PrimaryButton @click="save"> Kaydet </PrimaryButton>
    </template>
  </MdrModal>
</template>
