<template>
    <div
      class="tab-pane fade"
      id="user-set-information"
      role="tabpanel"
      aria-labelledby="user-set-information-tab"
    >
      <BCard no-body>
        <BCardHeader>
          <h5>اضافه کردن آدرس</h5>
        </BCardHeader>
        <BCardBody class="card-body">
          <BRow>
            <BCol class="col-sm-6">
              <div class="mb-3">
                <label class="form-label">طول جغرافیایی</label>
                <input
                  type="text"
                  v-model="lat"
                  class="form-control"
                  :class="{ 'is-invalid': errors.lat }"
                  placeholder="طول جغرافیایی"
                  @input="clearError('lat')"
                />
                <small v-if="errors.lat" class="text-danger">
                  {{ errors.lat }}
                </small>
              </div>
            </BCol>
            <BCol class="col-sm-6">
              <div class="mb-3">
                <label class="form-label">عرض جغرافیایی</label>
                <input
                  type="text"
                  v-model="long"
                  class="form-control"
                  placeholder="عرض جغرافیایی"
                  :class="{ 'is-invalid': errors.long }"
                  @input="clearError('long')"
                />
                <small v-if="errors.long" class="text-danger">
                  {{ errors.long }}
                </small>
              </div>
            </BCol>
            <BCol class="col-sm-12">
              <div id="map" style="height: 300px;"></div>
            </BCol>
            <BCol class="col-sm-6">
              <div class="mb-3">
                <label class="form-label">استان</label>
                <input
                  v-model="city"
                  type="text"
                  class="form-control"
                  :class="{ 'is-invalid': errors.city }"
                  placeholder="استان"
                  @input="clearError('city')"
                />
                <small v-if="errors.city" class="text-danger">
                  {{ errors.city }}
                </small>
              </div>
            </BCol>
            <BCol class="col-sm-6">
              <div class="mb-3">
                <label class="form-label">شهر</label>
                <input
                  v-model="town"
                  type="text"
                  class="form-control"
                  placeholder="شهر"
                  :class="{ 'is-invalid': errors.town }"
                  @input="clearError('town')"
                />
                <small v-if="errors.town" class="text-danger">
                  {{ errors.town }}
                </small>
              </div>
            </BCol>
            <BCol class="col-sm-6">
              <div class="mb-3">
                <label class="form-label">کد پستی</label>
                <input
                  v-model="postcode"
                  type="text"
                  class="form-control"
                  placeholder="کد پستی"
                  @input="clearError('postcode')"
                  :class="{ 'is-invalid': errors.postcode }"
                />
                <small v-if="errors.postcode" class="text-danger">
                  {{ errors.postcode }}
                </small>
              </div>
            </BCol>
            <BCol class="col-sm-6">
              <div class="mb-3">
                <label class="form-label">عنوان</label>
                <input
                  v-model="title"
                  type="text"
                  class="form-control"
                  placeholder="کد پستی"
                />
              </div>
            </BCol>
            <BCol class="col-sm-12">
              <div class="mb-3">
                <label class="form-label">آدرس</label>
                <textarea
                  v-model="address"
                  class="form-control"
                  placeholder="آدرس"
                  @input="clearError('address')"
                  :class="{ 'is-invalid': errors.address }"
                ></textarea>
                <small v-if="errors.address" class="text-danger">
                  {{ errors.address }}
                </small>
              </div>
            </BCol>
          </BRow>
        </BCardBody>
        <BCardFooter>
          <div class="text-center btn-page">
            <div @click="createAddress" class="btn btn-primary" :disabled="loading">
              <span v-if="loading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
              <span v-if="!loading">ثبت</span>
            </div>
          </div>
        </BCardFooter>
      </BCard>
    </div>
  </template>
  
  <script>
  import { ref, onMounted } from "vue";
  import { toast } from "vue3-toastify";
  import "vue3-toastify/dist/index.css";
  import ApiServiece from "@/services/ApiService";
  import L from "leaflet";
  import "leaflet/dist/leaflet.css";
  
  export default {
    setup() {
      const loading = ref(false);
      const title = ref();
      const address = ref();
      const lat = ref(51.505); // Default lat
      const long = ref(-0.09); // Default long
      const city = ref();
      const town = ref();
      const postcode = ref();
      const errors = ref({});
      let map;
      let marker;
  
      const validateForm = () => {
        errors.value = {};
        if (!address.value) errors.value.address = "وارد کردن آدرس الزامی می باشد";
        if (!lat.value) errors.value.lat = "وارد کردن عرض جغرافیایی الزامی می باشد";
        if (!long.value) errors.value.long = "وارد کردن طول جغرافیایی الزامی می باشد";
        if (!city.value) errors.value.city = "وارد کردن استان الزامی می باشد";
        if (!town.value) errors.value.town = "وارد کردن استان الزامی می باشد";
        if (!postcode.value) errors.value.postcode = "وارد کردن کد پستی الزامی می باشد";
        return Object.keys(errors.value).length === 0;
      };
  
      const clearError = (field) => {
        errors.value[field] = "";
      };
  
      const createAddress = () => {
        if (!validateForm()) return;
        loading.value = true;
        const formData = new FormData();
        formData.append("title", title.value);
        formData.append("address", address.value);
        formData.append("location[lat]", lat.value);
        formData.append("location[lng]", long.value);
        formData.append("city", city.value);
        formData.append("town", town.value);
        formData.append("postcode", postcode.value);
        ApiServiece.post(`wholesale/my-addresses`, formData)
          .then(() => {
            loading.value = false;
            toast.success("!آدرس با موفقیت اضافه شد", {
              position: "top-right",
              autoClose: 1000,
            });
          })
          .catch(() => {
            loading.value = false;
            toast.error("!مشکلی در ایجاد آدرس بوجود آمد", {
              position: "top-right",
              autoClose: 1000,
            });
          });
      };
  
      // Initialize map and marker
      onMounted(() => {
        map = L.map("map").setView([lat.value, long.value], 13);
  
        L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
          attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        }).addTo(map);
  
        marker = L.marker([lat.value, long.value]).addTo(map);
  
        map.on("click", function (e) {
          lat.value = e.latlng.lat;
          long.value = e.latlng.lng;
          marker.setLatLng(e.latlng);
        });
      });
  
      return {
        clearError,
        errors,
        createAddress,
        address,
        lat,
        long,
        postcode,
        town,
        city,
        title,
        loading,
      };
    },
  };
  </script>
  
  <style>
  #map {
    width: 100%;
    height: 300px;
  }
  </style>
  