<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-12">
            <BCard>
              <div id="map" style="height: 300px"></div>

              <!-- Display the address of the location -->
              <div v-if="mapAddress" class="address">
                <strong>آدرس:</strong> {{ mapAddress }}
              </div>
            </BCard>
          </BCol>
          <!-- Form fields for city, town, postcode, title, and address -->
          <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 L from "leaflet";
import "leaflet/dist/leaflet.css";
import { ref, toRef, watch, watchEffect, nextTick } from "vue";
import { toast } from "vue3-toastify";
import "vue3-toastify/dist/index.css";
import ApiServiece from "@/services/ApiService";

export default {
  props: {
    showCard: {
      type: Boolean,
    },
    orderId: {
      type: Number,
    },
    initMap: {
      type: Boolean,
    },
  },
  setup(props) {
    const localShowCard = toRef(props.showCard);
    const localOrderId = toRef(props.orderId);
    const loading = ref(false);
    const title = ref();
    const address = ref();
    const lat = ref();
    const long = ref();
    const city = ref();
    const town = ref();
    const postcode = ref();
    const addrerssId = ref();
    const errors = ref({});
    watch(
      () => props.showCard,
      (newVal) => (localShowCard.value = newVal)
    );

    watch(
      () => props.orderId,
      (newVal) => (localOrderId.value = newVal)
    );

    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((resp) => {
          loading.value = false;

          toast.success("!آدرس با موفقیت اضافه شد", {
            position: "top-right",
            autoClose: 1000,
          });

          console.log(resp);
          addrerssId.value = resp.data.data.id;
        })
        .catch(() => {
          loading.value = false;
          toast.error("!مشکلی در ایجاد آدرس بوجود آمد", {
            position: "top-right",
            autoClose: 1000,
          });
        });
    };

    const customIcon = new L.Icon({
      iconUrl: require("@/assets/images/location.svg"),
      iconSize: [32, 32], 
      iconAnchor: [16, 32], 
      popupAnchor: [0, -32], 
    });
    const currentLocation = ref([0, 0]); 
    const markerPosition = ref([32.6523, 51.6714]);
    const zoom = ref(13); 
    const typedAddress = ref(""); 
    const mapAddres = ref(null);
    let mapInstance = null;
    let marker = null;
    const getAddressFromLatLng = (lat, lng) => {
      const url = `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&addressdetails=1`;

      fetch(url)
        .then((response) => response.json())
        .then((data) => {
          if (data && data.address) {
            mapAddres.value = `${data.address.road || ""}, ${
              data.address.city || ""
            }, ${data.address.country || ""}`;
          }
        })
        .catch(() => {
          mapAddres.value = "Unable to fetch address.";
        });
    };

    // Function to search an address and get its location
    const searchAddress = () => {
      if (!typedAddress.value.trim()) return;

      const url = `https://nominatim.openstreetmap.org/search?q=${typedAddress.value}&format=json&addressdetails=1`;

      fetch(url)
        .then((response) => response.json())
        .then((data) => {
          if (data && data[0]) {
            const { lat, lon } = data[0];
            const latLng = [lat, lon];

            currentLocation.value = latLng;
            markerPosition.value = latLng;
            updateMapPosition();
            getAddressFromLatLng(lat, lon); // Get the address for the new location
          } else {
            address.value = "Address not found. Please try again.";
          }
        })
        .catch(() => {
          address.value = "Error fetching location.";
        });
    };

    const getCurrentLocation = () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          currentLocation.value = [
            position.coords.latitude,
            position.coords.longitude,
          ];

          lat.value = position.coords.latitude;
          long.value = position.coords.longitude;

          markerPosition.value = currentLocation.value;

          updateMapPosition();
          getAddressFromLatLng(lat.value, long.value);
        });
      } else {
        alert("Geolocation is not supported by this browser.");
      }
    };

    // Update the map's position based on the current location
    const updateMapPosition = () => {
      if (mapInstance) {
        mapInstance.setView(currentLocation.value, zoom.value);
      }
      if (marker) {
        marker.setLatLng(currentLocation.value);
      }
    };

    const initMap = () => {
      const defaultLocation = [32.6523, 51.6714];
      const savedLocation = JSON.parse(localStorage.getItem("userLocation"));
      const handleError = () => {
        console.error("An error occurred, using Isfahan as default.");
        setMapToLocation(defaultLocation);
      };

      if (savedLocation) {
        setMapToLocation(savedLocation);
      } else if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          const userLocation = [
            position.coords.latitude,
            position.coords.longitude,
          ];

          localStorage.setItem("userLocation", JSON.stringify(userLocation));
          setMapToLocation(userLocation);
        }, handleError);
      } else {
        console.error(
          "Geolocation is not supported, using Isfahan as default."
        );
        handleError();
      }

      function setMapToLocation(location) {
        if (!mapInstance) {
          mapInstance = L.map("map").setView(location, zoom.value);

          L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
            attribution:
              '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
          }).addTo(mapInstance);

          marker = L.marker(location, {
            draggable: false,
            icon: customIcon,
          })
            .addTo(mapInstance)
            .bindPopup("موقعیت شما")
            .openPopup();

          mapInstance.on("click", (e) => {
            const latLng = e.latlng;
            marker.setLatLng(latLng);
            lat.value = latLng.lat;
            long.value = latLng.lng;

            localStorage.setItem(
              "userLocation",
              JSON.stringify([lat.value, long.value])
            ); // Save new location
            getAddressFromLatLng(lat.value, long.value);
          });

          nextTick(() => {
            if (!mapInstance) {
              mapInstance.invalidateSize();
            }
          });
        }
      }
    };

    watchEffect(() => {
      setTimeout(() => {
        initMap();
        getCurrentLocation();
      }, 3000);
    });

    return {
      clearError,
      errors,
      createAddress,
      address,
      lat,
      long,
      postcode,
      town,
      city,
      title,
      loading,
      localShowCard,
      localOrderId,
      currentLocation,
      markerPosition,
      zoom,
      typedAddress,
      mapAddres,
      searchAddress,
    };
  },
};
</script>
<style scoped>
#map {
  height: 300px;
  width: 100%;
}
.address {
  text-align: center;
}
</style>
