<!-- eslint-disable vue/valid-v-for -->
<template>
  <div>
    <div class="q-mt-md">
      <q-breadcrumbs class="q-mb-md" active-color="black">
        <template v-slot:separator>
          <q-icon size="1.5em" name="chevron_right" color="black" />
        </template>
        <q-breadcrumbs-el label="Laca" icon="home" to="/" />
        <q-breadcrumbs-el label="Chỗ đỗ xe xung quanh" />
      </q-breadcrumbs>
      <div class="float-right items-end">
        <q-toggle
          class="justify-end float-right"
          v-model="isFindNear"
          color="primary"
          keep-color
          label="Tìm kiếm xung quanh"
        />
      </div>

      <MglMap
        :map-style="mapStyle"
        :center="center"
        :zoom="zoom"
        height="calc(100vh - 120px)"
      >
        <MglNavigationControl />
        <MglGeolocateControl
          :showAccuracyCircle="false"
          :showUserLocation="false"
        />
        <MglCustomControl position="top-right">
          <q-btn
            icon="list"
            @click="showListMarkerInfo = !showListMarkerInfo"
          />
        </MglCustomControl>
        <MglMarker v-if="currentPosition" :coordinates="currentPosition" />

        <MglMarker
          v-for="(marker, index) in listMarker"
          :coordinates="marker"
          :key="index"
          color="#1976D2"
          :ref="`popup_${marker.id}`"
        >
          <template
            v-slot:marker
            v-if="activeMarker.id !== marker.id && !activeMarker.id"
          >
            <div
              :class="`col-auto text-grey-9 text-caption row items-center text-weight-regular q-pa-xs marker-item ${
                activeMarker.id === marker.id ? 'marker-item-active' : ''
              }`"
            >
              <!-- <span class="text-subtitle1 text-weight-bold">
                {{ marker.name }}
              </span>
              <span class="text-subtitle1 text-weight-bold"> - </span> -->
              <span class="text-subtitle1 text-weight-bold">
                {{ currencyFormatter.format(+marker.pricing_per_hour) }}
              </span>
            </div>
          </template>
          <MglPopup
            maxWidth="340px"
            anchor="bottom-left"
            :subpixelPositioning="true"
            :closeOnMove="true"
          >
            <q-card
              flat
              bordered
              :class="`card-popup-${$q.screen.gt.sm ? 'md' : 'sm'}`"
            >
              <div class="q-pa-md">
                <q-carousel
                  v-model="slide"
                  transition-prev="scale"
                  transition-next="scale"
                  swipeable
                  animated
                  control-color="white"
                  navigation
                  padding
                  arrows
                  :height="$q.screen.gt.sm ? '250px' : '175px'"
                  :width="$q.screen.gt.sm ? '300px' : '150px'"
                  class="bg-gray text-white shadow-1 rounded-borders"
                >
                  <q-carousel-slide
                    v-for="(item, i) in marker?.images || []"
                    :name="i + 1"
                    :img-src="getImageUrl(marker?.images, i)"
                  />
                </q-carousel>
              </div>
              <q-card-section class="q-py-sm">
                <div class="row no-wrap items-center">
                  <div class="col text-h6 ellipsis">
                    {{ marker.name }}
                  </div>
                </div>
                <div class="text-grey-7">
                  {{ `${marker.address}, ${marker.district}, ${marker.ward}` }}
                </div>
                <div class="row justify-between">
                  <div
                    class="col-auto text-grey-9 text-caption row items-center text-weight-regular"
                  >
                    <span class="text-subtitle1 text-weight-bold">
                      {{ currencyFormatter.format(+marker.pricing_per_hour) }}
                    </span>
                    &nbsp;/ h
                  </div>
                  <q-btn
                    color="secondary"
                    size="small"
                    rounded
                    @click="showReserve(marker)"
                  >
                    Đặt chỗ
                  </q-btn>
                </div>
              </q-card-section>
            </q-card>
          </MglPopup>
        </MglMarker>
        <!-- Locate  -->
        <MglMarker
          v-if="activeMarker?.marker"
          :coordinates="activeMarker.position"
        />
        <MglPopup
          v-if="activeMarker?.marker"
          :coordinates="activeMarker.position"
          anchor="bottom-left"
          :close-button="false"
          @close="
            activeMarker = {
              marker: null,
              id: null,
              position: { lat: 0, lng: 0 },
            }
          "
          :class="`card-popup-${$q.screen.gt.sm ? 'md' : 'sm'}`"
        >
          <q-card
            flat
            bordered
            :class="`card-popup-${$q.screen.gt.sm ? 'md' : 'sm'}`"
          >
            <div class="q-pa-md">
              <q-carousel
                v-model="slide"
                transition-prev="scale"
                transition-next="scale"
                swipeable
                animated
                control-color="white"
                navigation
                padding
                arrows
                :height="$q.screen.gt.sm ? '250px' : '175px'"
                :width="$q.screen.gt.sm ? '300px' : '150px'"
                class="bg-gray text-white shadow-1 rounded-borders"
              >
                <q-carousel-slide
                  v-for="(item, i) in activeMarker?.marker?.images || []"
                  :name="i + 1"
                  :img-src="getImageUrl(activeMarker?.marker?.images, i)"
                />
              </q-carousel>
            </div>
            <q-card-section class="q-py-sm">
              <div class="row no-wrap items-center">
                <div class="col text-h6 ellipsis">
                  {{ activeMarker?.marker?.name }}
                </div>
              </div>
              <div class="text-grey-7">
                {{
                  `${activeMarker?.marker?.address}, ${activeMarker?.marker?.district}, ${activeMarker?.marker?.ward}`
                }}
              </div>
              <div class="row justify-between">
                <div
                  class="col-auto text-grey-9 text-caption row items-center text-weight-regular"
                >
                  <span class="text-subtitle1 text-weight-bold">
                    {{
                      currencyFormatter.format(
                        +activeMarker?.marker?.pricing_per_hour
                      )
                    }}
                  </span>
                  &nbsp;/ h
                </div>
                <q-btn
                  color="secondary"
                  size="small"
                  rounded
                  @click="showReserve(activeMarker?.marker)"
                >
                  Đặt chỗ
                </q-btn>
              </div>
            </q-card-section>
          </q-card>
        </MglPopup>
      </MglMap>

      <q-dialog
        v-model="showListMarkerInfo"
        class="list-parking"
        seamless
        :position="`${$q.screen.gt.sm ? 'left' : 'bottom'}`"
      >
        <div
          :class="`markers-${$q.screen.gt.sm ? 'md' : 'sm'} bg-white q-pa-md`"
          @scroll="onScroll"
        >
          <q-toolbar>
            <q-toolbar-title
              >{{$t('packingMap.have')}}<span class="text-weight-bold">
                {{ ` ${this.listMarker.length}` }}</span
              >
              {{$t('packingMap.result')}}</q-toolbar-title
            >

            <q-btn flat round dense icon="close" v-close-popup />
          </q-toolbar>
          <div class="row q-gutter-sm justify-evenly q-pb-sm">
            <q-card
              flat
              bordered
              :class="`col-sm-12 col-md-5 card-projects q-pa-none ${
                activeMarker.id === n.id ? 'active' : ''
              }`"
              v-for="(n, idx) in listMarker"
              :key="n.id"
              :id="idx"
            >
              <q-card-section horizontal class="q-card-section-fixed-height">
                <q-card-section class="q-pt-xs content-section">
                  <div
                    class="text-grey text-caption q-pt-md row no-wrap items-center"
                  >
                    {{ `${currencyFormatter.format(+n.pricing_per_hour)}` }}
                  </div>
                  <div class="text-h5 q-mt-sm q-mb-xs ellipsis">
                    {{ n.name }}
                  </div>
                  <div class="text-caption text-grey">{{ n.address }}</div>
                </q-card-section>

                <q-card-section class="col-5 flex flex-center">
                  <q-img class="rounded-borders" :src="getImageUrl(n.images)" />
                </q-card-section>
              </q-card-section>

              <q-separator />

              <q-card-actions>
                <q-btn color="primary" @click="showReserve(n)"> Đặt chỗ </q-btn>

                <q-btn
                  padding="sm"
                  fab
                  color="primary"
                  icon="place"
                  @click="selectMarker(n, idx)"
                />
                <q-btn
                  padding="sm"
                  fab
                  color="primary"
                  icon="map"
                  @click="gotoDirections(n.lat, n.lng)"
                />
              </q-card-actions>
            </q-card>
            <div class="q-gutter-md row justify-center" style="font-size: 2em">
              <q-spinner
                v-if="loadMarker"
                color="primary"
                size="50px"
                class="q-mt-md"
                style="font-size: 2em"
              />
            </div>
          </div>
        </div>
      </q-dialog>
    </div>
  </div>
</template>
<script lang="ts">
import dayjs from 'dayjs';
import { defineComponent, isProxy, ref } from 'vue';
import { mapGetters, mapActions } from 'vuex';
import {
  MglMap,
  MglMarker,
  MglNavigationControl,
  MglPopup,
  MglGeolocateControl,
  MglCustomControl,
} from '@indoorequal/vue-maplibre-gl';

export default defineComponent({
  name: 'ParkingMap',
  components: {
    MglMap,
    MglMarker,
    MglNavigationControl,
    MglPopup,
    MglGeolocateControl,
    MglCustomControl,
  },

  data() {
    return {
      options: ['Car', 'Mortorbike', 'Orther'],
      currencyFormatter: new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND',
      }),
      reserveData: {
        licensePlates: '',
        start: dayjs().format('YYYY-MM-DD HH:mm').toString(),
        end: '',
        name: '',
        id: null,
        contact: '',
        carType: '',
      },
      reserveDialog: false,
      showListMarkerInfo: true,
      mapStyle: `https://api.maptiler.com/maps/streets/style.json?key=${process.env.VUE_APP_API_KEY_STYLE_MAP}`,
      center: { lat: 21.028511, lng: 105.804817 },
      currentPosition: { lat: 0, lng: 0 },
      origin: '',
      destination: '',
      map: null,
      // directionsService: new google.maps.DirectionsService(),
      // directionsRenderer: new google.maps.DirectionsRenderer(),
      listMarker: [],
      activeMarker: {
        marker: null,
        id: null,
        position: { lat: 0, lng: 0 },
      },
      slide: ref(1),
      isFindNear: false,
      cursorId: null,
      action: 'next',
      loadMarker: false,
      itemRefs: {} as Record<number, HTMLButtonElement>,
      zoom: 14,
    };
  },
  mounted() {
    if (this.isFindNear) this.loadNearSlot();
    else this.loadPacking();
  },
  computed: {
    ...mapGetters({
      getUser: 'userModule/getUser',
    }),
  },
  watch: {
    isFindNear() {
      if (this.isFindNear) this.loadNearSlot();
      else this.loadPacking();
    },
  },
  methods: {
    ...mapActions({
      getListSlotNear: 'slotModule/getListSlotNear',
      bookingSlot: 'slotModule/bookingSlot',
      detailSlot: 'slotModule/detailSlot',
      changeReserveDialog: 'slotModule/changeReserveDialog',
      changeCurrentId: 'slotModule/changeCurrentId',
      getListSlot: 'slotModule/getListSlot',
      getListSlotByCursor: 'slotModule/getListSlotByCursor',
    }),
    async loadPacking() {
      this.loadMarker = true;
      const res = await this.getListSlotByCursor({ cursorId: this.cursorId });
      this.listMarker = this.listMarker.concat(res.data.slots);
      this.cursorId = this.listMarker[this.listMarker.length - 1].id;
      if (this.listMarker.length) {
        this.center = {
          lat: parseFloat(this.listMarker[0].lat),
          lng: parseFloat(this.listMarker[0].lng),
        };
        this.currentPosition = null;
        this.loadMarker = false;
      }
    },
    async loadNearSlot() {
      try {
        navigator.geolocation.getCurrentPosition(this.showPosition);
      } catch (error) {
        console.log(error);
      }
    },
    async showPosition(position: any) {
      let detailSelect = null;
      this.center = {
        lat: parseFloat(position.coords.latitude),
        lng: parseFloat(position.coords.longitude),
      };
      this.currentPosition = this.center;

      const res = await this.getListSlotNear(this.center);
      this.listMarker = res.data.slots;
      if (this.$route.query.id) {
        const resDetail = await this.detailSlot({ id: this.$route.query.id });
        detailSelect = <any>resDetail.data;
        this.listMarker = [detailSelect];
        this.center = {
          lat: parseFloat(detailSelect?.lat),
          lng: parseFloat(detailSelect?.lng),
        };
        this.showListMarkerInfo = false;
        // if (!isExistSlot) this.listMarker.push(detailSelect);
      }
    },
    onMapLoad() {
      console.log(1);
    },
    gotoDirections(lat: number, lng: number) {
      const routeData = {
        href: `https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`,
      };
      window.open(routeData.href, '_blank');
    },
    selectMarker(marker: any, idx: any) {
      this.zoom = 14;
      this.activeMarker = {
        marker: marker,
        id: marker.id,
        position: {
          lat: parseFloat(marker.lat),
          lng: parseFloat(marker.lng),
        },
      };
      this.center = this.activeMarker.position;
      if (this.$q.screen.lt.sm) {
        this.showListMarkerInfo = false;
        this.center = {
          lat: parseFloat(marker.lat) + 0.003,
          lng: parseFloat(marker.lng) + 0.003,
        };
      }
    },
    showReserve(reserve: any) {
      // this.reserveDialog = true;
      // this.reserveData.id = reserve.id;
      this.changeReserveDialog();
      this.changeCurrentId(reserve.id);
      this.showListMarkerInfo = false;
    },
    async bookingHandle() {
      const params = {
        owner: this.reserveData.name,
        licensePlates: this.reserveData.licensePlates,
        contact: this.reserveData.contact,
        slotId: this.reserveData.id,
        startAt: this.reserveData.start,
        endAt: this.reserveData.end,
        carType: this.reserveData.carType,
      };
      await this.bookingSlot(params);
      this.reserveDialog = false;
      this.reserveData.id = null;
    },
    getImageUrl(images: [], index: number | null = null) {
      if (!images?.length) {
        return '/icons/logos/LACA_transparent2.png';
      }
      if (index == null) {
        const random = Math.floor(Math.random() * images.length);
        return `${process.env.VUE_APP_API_SERVER}/files/upload/${images[random]}`;
      }
      return `${process.env.VUE_APP_API_SERVER}/files/upload/${images[index]}`;
    },
    async onScroll({ target: { scrollTop, clientHeight, scrollHeight } }) {
      if (scrollTop + clientHeight >= scrollHeight) {
        await this.loadPacking();
      }
    },
    setPopupRef(id, el) {
      if (el) {
        this.itemRefs[id] = el;
      }
    },
  },
});
</script>

<style lang="scss">
@import 'maplibre-gl/dist/maplibre-gl.css';

#map {
  min-height: calc(100vh - 140px);
}

.q-page-container {
  position: relative;

  .maplibregl-popup {
    border-radius: 16px;

    .maplibregl-popup-content {
      padding: 0;
      border-radius: 16px;

      .q-card {
        border-radius: 16px;
      }

      .maplibregl-popup-close-button {
        background: #fff;
        border-radius: 20px;
        top: 5px;
        right: 5px;
        font-size: 15px;
      }
    }
  }
}

.list-parking {
  z-index: 9999;

  .q-dialog__inner {
    padding: 0;
    top: unset;
  }

  .markers {
    &-md {
      min-width: 660px;
      height: calc(100vh - 62px);
    }

    &-sm {
      width: 100vw;
      height: 50vh;
    }
  }

  .q-card {
    // width: 300px;
    height: 300px;
    width: 300px;
    border-radius: 15px;

    &.active {
      border: 1px solid #0499a8;
    }

    .price {
      font-weight: bold;
      color: #0499a8;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.card-popup {
  &-md {
    width: 300px;
  }

  &-sm {
    width: 200px;
  }
}

.marker-item {
  border: 1px solid;
  border-radius: 10px;
  background-color: #fff;
  border: 1px solid #1976d2;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.2);
}

.marker-item-active {
  background-color: #1976d2;
  color: #fff;
  z-index: 9999;
}

/* Fixed height for the card sections */
.q-card-section-fixed-height {
  height: 80%; /* Adjust this value as needed */
}

/* Ensure content section doesn't overflow */
.content-section {
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* Make image section maintain aspect ratio */
.image-section {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Make images consistent */
.image-section .q-img {
  height: 120px; /* Adjust as needed */
  width: 100%;
  object-fit: cover;
}
</style>
