<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<template>
  <div class="location-container q-pa-md">
    <div class="row justify-end">
      <div class="col-4 float-left q-mb-10">
        <q-btn
          class="float-right"
          color="primary"
          label="Đặt Chỗ"
          @click="showReserve"
        />
      </div>
    </div>
    <!-- <h2 class="text-h5 q-mb-md">Nơi bạn sẽ đến</h2> -->

    <div class="map-container q-mb-md q-mt-md">
      <div class="map-wrapper">
        <MglMap
          :map-style="mapStyle"
          :center="currentPosition"
          :zoom="15"
          height="calc(100vh - 120px)"
        >
          <MglNavigationControl />
          <MglGeolocateControl
            :showAccuracyCircle="false"
            :showUserLocation="false"
          />
          <MglCustomControl position="top-right">
            <q-btn icon="list" @click="true" />
          </MglCustomControl>
          <MglMarker :coordinates="currentPosition" />
        </MglMap>
      </div>
    </div>

    <div class="location-details">
      <!-- <h2 class="text-h5 q-mb-md">{{  }}</h2> -->
      <div class="property-header q-py-md">
        <h1 class="text-h5 text-weight-bold q-mb-xs">
          {{ packing.name }}
        </h1>
        <div class="property-details q-mb-xs">
          <span>{{ packingAddress }}</span>
        </div>
        <div class="rating-container">
          <div class="rating">
            <q-icon name="star" size="16px" color="black" />
            <span class="rating-value">{{ packing.vote || 0 }}</span>
            <span class="rating-count">· {{ totalComment }} đánh giá</span>
          </div>
        </div>
      </div>
      <div class="property-header q-py-md">
        <h1 class="text-h5 text-weight-bold q-mb-xs">
          Mô Tả
        </h1>
        <div class="property-details q-mb-xs">
          <p class="description">{{ destination }}</p>
        </div>
      </div>
      <div class="amenities-section q-py-lg">
        <h2 class="text-h5 text-weight-bold q-mb-md">Thông tin chỗ đậu xe</h2>

        <div class="row q-col-gutter-md">
          <!-- Left Column -->
          <div class="col-12 col-sm-6">
            <div class="amenity-item q-mb-md">
              <q-icon
                name="payments"
                size="24px"
                color="dark"
                class="q-mr-sm"
              />
              <span>{{
                new Intl.NumberFormat('vi-VN', {
                  style: 'currency',
                  currency: 'VND',
                }).format(packing.pricing_per_hour)
              }}</span>
            </div>
            <div class="amenity-item q-mb-md">
              <q-icon
                name="123"
                size="24px"
                color="dark"
                class="q-mr-sm"
              />
              <span>Tổng số <span class="text-weight-bold">{{
                `${packing.empty}/${packing.total}`
              }}</span> Chỗ đỗ</span>
            </div>


            <div class="amenity-item q-mb-md">
              <q-icon
                name="schedule"
                size="24px"
                color="dark"
                class="q-mr-sm"
              />
              <span class="text-weight-bold" >{{ formatTime(packing.open, "00:00") }} <span > - </span>  {{formatTime(packing.close, "24:00")}}</span>
            </div>
          </div>


          <!-- Right Column -->
          <div class="col-12 col-sm-6">
            <div class="amenity-item q-mb-md">
              <q-icon name="info" size="24px" color="dark" class="q-mr-sm" />
              <span>Dành cho <span class="text-weight-bold" >{{ covertAlowBookingType(packing.alow_booking_type) }}</span></span>
            </div>

          </div>
        </div>
      </div>


    </div>


    <q-separator class="q-mt-lg q-mb-lg" />

    <!-- Comments Section -->
    <div class="comments-section">
      <div class="row">
        <div class="col">
          <h2 class="text-h5 text-weight-bold q-mb-md">Đánh giá</h2>
        </div>
        <div class="col d-flex justify-content-center center-block"></div>
      </div>

      <div class="comments-stats q-mb-lg">
        <div class="rating-summary">
          <div class="rating-average">
            <span class="rating-number">{{ averageRating }}</span>
            <div class="rating-stars">
              <q-rating
                v-model="averageRating"
                max="5"
                size="1.2em"
                color="primary"
                @click="changeRating"

              />
            </div>
          </div>
        </div>
      </div>

      <!-- Comments List -->
      <div class="comments-list">
        <div
          v-for="(comment, index) in comments"
          :key="index"
          class="comment-card q-mb-lg"
        >
          <div class="comment-header">
            <div class="user-info">
              <q-avatar size="48px">
                <img :src="comment.avatar" />
              </q-avatar>
              <div class="user-details">
                <div class="user-name">{{ comment.name }}</div>
                <div class="comment-date">{{ comment.date }}</div>
              </div>
            </div>
          </div>

          <div class="comment-content q-mt-sm">
            <p class="comment-text">{{ comment.text }}</p>

            <!-- <div v-if="comment.response" class="host-response q-mt-md q-pa-md">
              <div class="response-header q-mb-sm">
                <span class="response-from">Phản hồi từ chủ nhà:</span>
              </div>
              <p class="response-text">{{ comment.response }}</p>
            </div> -->

            <div class="comment-actions q-mt-sm">
              <q-btn
                flat
                dense
                size="sm"
                class="helpful-btn"
                @click="reactCommnent(comment.id)"
              >
                <q-icon name="thumb_up_off_alt" size="1em" class="q-mr-xs" />
                Hữu ích
              </q-btn>
              <span
                v-if="comment.helpfulCount > 0"
                class="helpful-count q-ml-sm"
              >
                {{ comment.helpfulCount }} người thấy hữu ích
              </span>
            </div>
          </div>

          <q-separator v-if="index < comments.length - 1" class="q-mt-lg" />
        </div>
      </div>
      <div>
        <form @submit.prevent="submitComment" class="q-pa-md">
          <!-- a simple text field watching for the enter key release -->
          <q-input
            filled
            color="teal"
            hint="Type then hit Enter key above"
            v-model="content"
            autocorrect="off"
            autocapitalize="off"
            autocomplete="off"
            spellcheck="false"
          />
          <div class="row justify-end">
            <q-btn
              type="submit"
              :loading="loading"
              label="Nhận Xét"
              class="q-mt-md"
              size="sm"
              color="primary"
            >
              <template v-slot:loading>
                <q-spinner-facebook />
              </template>
            </q-btn>
          </div>
        </form>
      </div>
      <!-- Show More Comments Button -->
      <div class="q-pa-lg flex flex-cemter justify-center">
        <q-pagination
          v-model="pagination.page"
          direction-links
          flat
          @update:model-value="loadComment"
          :max="pagesNumber"
          :max-pages="5"
          :ellipses="false"
          :boundary-numbers="false"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'src/store';
import dayjs from 'dayjs';
import {
  MglMap,
  MglMarker,
  MglNavigationControl,
  MglGeolocateControl,
  MglCustomControl,
} from '@indoorequal/vue-maplibre-gl';
const store = useStore();
const route = useRoute();
// Average rating
const averageRating = ref(0);
const mapStyle = `https://api.maptiler.com/maps/streets/style.json?key=${process.env.VUE_APP_API_KEY_STYLE_MAP}`;
const currentPosition = ref({ lat: 0, lng: 0 });
const packingAddress = ref('');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const comments = ref<any[]>([]);
const totalComment = ref(0)
const packing = ref({});
const content = ref('');
const loading = ref(false);
const destination = ref('Chưa có mô tả');
const pagination = ref({
  page: 1,
  rowsPerPage: 5,
});
const pagesNumber = ref(1);

const changeRating = async () => {
  if (!store.getters['userModule/getUser']) {
    store.$router.push({ name: 'login' });
  }
  try {
    await store.dispatch('slotModule/rateSlot', {
      id: +route.params.id,
      data: {source:averageRating.value}  // value},
    });
    await loadPacking();
  } catch (error) {
    console.log(error);
  }
};
const loadComment = async () => {
  const params = {
    pageSize: pagination.value.rowsPerPage,
    pageNumber: pagination.value.page,
  };
  const { data: commentData } = await store.dispatch(
    'commentModule/getListComment',
    { id: +route.params.id, pagination: params }
  );
  totalComment.value = commentData.total;
  pagesNumber.value = Math.ceil(
    commentData.total / pagination.value.rowsPerPage
  );
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  comments.value = commentData.comments?.map((e: any) => {
    const now = dayjs(e.createdAt);
    return {
      id: e.id,
      name: e.user.fullname,
      avatar: '/images/default_user_icon_4.jpg',
      date: `Ngày ${now.format('D')}  Tháng ${now.format('M')} năm ${now.format(
        'YYYY'
      )}`,
      text: e.content,
      helpfulCount: e._count?.likes,
      response: '',
    };
  });
};
const loadPacking = async () => {
  const { data: packingData } = await store.dispatch(
    'slotModule/detailSlot',
    route.params
  );
  packing.value = packingData;
  packingAddress.value = [
    packingData.address,
    packingData.district,
    packingData.ward,
    packingData.city,
  ]
    .filter((e) => e)
    .join(', ');

  currentPosition.value = {
    lat: packingData.lat,
    lng: packingData.lng,
  };

  if (packingData.destination && `${packingData.destination}`.length) {
    destination.value = packingData.destination;

  }
  // averageRating.value = packingData.vote;
};
onMounted(async () => {
  await loadPacking();
  await loadComment();
  if (store.getters['userModule/getUser']) {
    const { data: rateData } = await store.dispatch(
    'slotModule/getRateSlot', +route.params.id
    );
    averageRating.value = rateData?.source || 0;

  }
});

const showReserve = () => {
  // this.reserveDialog = true;
  // this.reserveData.id = reserve.id;
  store.dispatch('slotModule/changeReserveDialogs');
  store.dispatch('slotModule/changeReserveDialog', +route.params.id);
};
const reactCommnent = async (id: number | string) => {
  try {
    loading.value = true;
    const response = await store.dispatch('commentModule/reactComment', {
      id,
    });
    content.value = '';
    await loadComment();
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
const formatTime = (date: string, defaultValue = '') => {
  try {
    if (!date) {
      return defaultValue;
    }
  return date;

  } catch (error) {
    return '__:__'
  }
};

const covertAlowBookingType = (type: string) => {
  switch (type) {
    case 'Car':
      return 'Ô tô';
    case 'All':
      return 'Ô tô và xe máy';
    case 'Motorbike':
      return 'Xe máy';
    default:
      return '';
  }
};
const submitComment = async () => {
  if (!store.getters['userModule/getUser']) {
    store.$router.push({ name: 'login' });
  }
  const commentParams = {
    content: content.value,
    slot_id: +route.params.id,
  };
  try {
    loading.value = true;
    const response = await store.dispatch(
      'commentModule/addComment',
      commentParams
    );
    content.value = '';
    await loadComment();
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.location-container {
  max-width: 75%;
  margin: 0 auto;
  font-family: 'Circular', -apple-system, BlinkMacSystemFont, Roboto,
    'Helvetica Neue', sans-serif;
}

.map-container {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.map-wrapper {
  position: inherit;
  height: 380px;
}

.map-image {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

.map-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.zoom-controls {
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.control-btn {
  background: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.location-btn {
  background: white;
  color: #ff385c;
}

.location-marker {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 48px;
  height: 48px;
  background: rgba(255, 56, 92, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-popup {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  max-width: 250px;
  z-index: 10;
}

.popup-content {
  font-size: 14px;
  color: #222;
}

.map-attribution {
  display: flex;
  justify-content: space-between;
  padding: 6px 12px;
  background: #f8f8f8;
  font-size: 12px;
  color: #717171;
}

.location-details {
  padding: 16px 0;
}

.show-more-btn {
  padding: 0;
  color: #222;
  font-weight: 500;
  text-decoration: underline;
  display: flex;
  align-items: center;
}

/* Comments Section Styles */
.comments-section {
  padding: 16px 0;
}

.comments-stats {
  margin-bottom: 32px;
}

.rating-summary {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.rating-average {
  display: flex;
  align-items: center;
}

.rating-number {
  font-size: 22px;
  font-weight: 600;
  margin-right: 8px;
}

.rating-count {
  color: #717171;
  margin-left: 4px;
}

.rating-categories {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.rating-category {
  display: flex;
  align-items: center;
}

.category-name {
  width: 80px;
  font-size: 14px;
}

.category-bar-container {
  flex: 1;
  height: 4px;
  background-color: #ebebeb;
  border-radius: 2px;
  margin: 0 12px;
}

.category-bar {
  height: 100%;
  background-color: #222222;
  border-radius: 2px;
}

.category-score {
  font-size: 14px;
  width: 30px;
  text-align: right;
}

.comment-card {
  padding: 8px 0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 600;
  font-size: 16px;
}

.comment-date {
  color: #717171;
  font-size: 14px;
}

.comment-text {
  font-size: 16px;
  line-height: 1.5;
  margin: 0;
}

.host-response {
  background-color: #f8f8f8;
  border-radius: 8px;
}

.response-from {
  font-weight: 600;
  font-size: 14px;
}

.response-text {
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

.comment-actions {
  display: flex;
  align-items: center;
}

.helpful-btn {
  color: #717171;
  font-size: 14px;
  padding: 4px 8px;
}

.helpful-count {
  color: #717171;
  font-size: 14px;
}

.show-more-comments-btn {
  padding: 12px 24px;
  font-weight: 600;
  border-radius: 8px;
}

@media (min-width: 768px) {
  .rating-summary {
    flex-direction: row;
    justify-content: space-between;
  }

  .rating-average {
    width: 30%;
  }

  .rating-categories {
    width: 65%;
  }
}

@media (max-width: 600px) {
  .map-wrapper {
    height: 300px;
  }

  .info-popup {
    max-width: 200px;
  }

  .rating-categories {
    grid-template-columns: 1fr;
  }

  .comment-text {
    font-size: 14px;
  }

  .description {
    text-align: justify;
    line-height: 1.75em;
    width: 100%;
    clear: both;
    font-size: 14px;
}
}
</style>
