<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 formData = ref({
  company: "",
  name: "",
  surname: "",
  tckn: "",
  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.tckn = seller.data.store_info.tckn || seller.data.tckn || "";
  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 = "";
  formData.value.address = seller.data.address.street_1;
};
</script>

<template>
  <MdrModal v-model="isOpen" size="max-w-4xl" @on-hide="closeModal">
    <template #title> {{ $t("seller_details_title") }} </template>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <template
        v-for="field in [
          { model: 'company', label: 'company_name' },
          { model: 'name', label: 'person_name' },
          { model: 'surname', label: 'person_surname' },
          { model: 'tckn', label: 'person_tckn' },
          { model: 'phone', label: 'phone' },
          { model: 'email', label: 'email' },
          { model: 'city', label: 'city' },
          { model: 'district', label: 'district' },
          { model: 'neighborhood', label: 'neighborhood' },
          { model: 'address', label: 'address' },
        ]"
        :key="field.model"
      >
        <div
          :class="
            field.model === 'company' || field.model === 'address'
              ? 'col-span-2'
              : ''
          "
        >
          <MdrFormField
            v-model="formData[field.model]"
            :label="$t(field.label)"
            required
            auto-complete=""
            type="text"
            :placeholder="`${$t(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>
