<template>
  <q-page class="q-pa-md">
    <!-- 네이버 지도: 스팟 마커 표시, 마커 클릭 시 해당 스팟 선택 -->
    <q-card flat bordered class="q-mb-md overflow-hidden">
      <NaverMap :spots="spots" :selected-id="currentSpot?.id ?? null" @select="onSelectSpot" />
    </q-card>

    <!-- 로딩 / 에러 -->
    <q-banner v-if="loadError" dense class="bg-red-1 text-red-8 q-mb-md rounded-borders">
      <template #avatar><q-icon name="wifi_off" /></template>
      백엔드에 연결하지 못했습니다. (서버 실행 여부를 확인하세요)
    </q-banner>

    <!-- 체크인 -->
    <q-btn
      color="primary"
      class="full-width q-py-sm"
      unelevated
      :loading="checkingIn"
      :disable="!currentSpot"
      icon="place"
      :label="checkedIn ? '체크인 완료 · 여기 있어요!' : '나 지금 여기 도착!'"
      @click="onCheckIn"
    />

    <!-- 스팟 한줄평 (네이버 지도식 태그형) -->
    <div class="text-subtitle1 text-weight-bold q-mt-lg q-mb-sm">
      {{ currentSpot ? currentSpot.name : '스팟' }} · 오늘의 한줄평
    </div>
    <div v-if="reviews.length" class="row q-gutter-sm">
      <q-chip
        v-for="review in reviews"
        :key="review.id"
        color="secondary"
        text-color="accent"
        icon="tag"
      >
        {{ review.tag || review.content }}
      </q-chip>
    </div>
    <div v-else class="text-caption text-grey-5">아직 한줄평이 없어요.</div>

    <!-- 현재 체크인 중인 메이트 -->
    <div class="text-subtitle1 text-weight-bold q-mt-lg q-mb-sm">지금 이 스팟의 산책 메이트</div>
    <div v-if="!mates.length" class="text-caption text-grey-5">체크인 중인 메이트가 없어요.</div>
    <q-card v-for="mate in mates" :key="mate.dogId" flat bordered class="q-mb-sm">
      <q-item>
        <q-item-section avatar>
          <q-avatar color="secondary" text-color="accent" icon="pets" />
        </q-item-section>
        <q-item-section>
          <q-item-label class="text-weight-medium">{{ mate.name }}</q-item-label>
          <q-item-label caption>{{ mate.breed || '견종 미상' }}</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-btn
            dense
            unelevated
            color="primary"
            icon="favorite"
            label="매칭"
            :loading="matchingDogId === mate.dogId"
            @click="onMatch(mate)"
          />
        </q-item-section>
      </q-item>
    </q-card>
  </q-page>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useQuasar } from 'quasar'
import { spotsApi, type Mate, type Review, type Spot } from '@/api/spots'
import { matchesApi } from '@/api/matches'
import { ApiError } from '@/api/http'
import { useAuthStore } from '@/stores/auth'
import { useDogsStore } from '@/stores/dogs'
import NaverMap from '@/components/NaverMap.vue'

const $q = useQuasar()
const auth = useAuthStore()
const dogs = useDogsStore()

// 체크인/매칭 주체: 로그인 회원 + 대표 강아지
const currentUserId = () => auth.member?.id ?? 0

const spots = ref<Spot[]>([])
const currentSpot = ref<Spot | null>(null)
const reviews = ref<Review[]>([])
const mates = ref<Mate[]>([])
const checkedIn = ref(false)
const checkingIn = ref(false)
const matchingDogId = ref<number | null>(null)
const loadError = ref(false)

onMounted(load)

async function load() {
  loadError.value = false
  try {
    await dogs.loadMyDogs()
    spots.value = await spotsApi.list()
    currentSpot.value = spots.value[0] ?? null
    if (currentSpot.value) {
      await refreshSpot(currentSpot.value.id)
    }
  } catch (e) {
    loadError.value = true
    console.error(e)
  }
}

async function onSelectSpot(spotId: number) {
  const spot = spots.value.find((s) => s.id === spotId)
  if (!spot) return
  currentSpot.value = spot
  checkedIn.value = false
  await refreshSpot(spotId)
}

async function refreshSpot(spotId: number) {
  const [r, m] = await Promise.all([spotsApi.reviews(spotId), spotsApi.mates(spotId)])
  reviews.value = r
  mates.value = m
}

async function onCheckIn() {
  if (!currentSpot.value) return
  if (dogs.currentDogId == null) {
    $q.notify({ color: 'warning', message: '먼저 우리 개를 등록해 주세요.', icon: 'pets', position: 'top' })
    return
  }
  checkingIn.value = true
  try {
    await spotsApi.checkIn(currentSpot.value.id, currentUserId(), dogs.currentDogId)
    checkedIn.value = true
    await refreshSpot(currentSpot.value.id)
    $q.notify({ color: 'primary', message: '체크인 완료! 스팟 채팅이 열렸어요.', icon: 'place', position: 'top' })
  } catch (e) {
    notifyError(e)
  } finally {
    checkingIn.value = false
  }
}

async function onMatch(mate: Mate) {
  if (dogs.currentDogId == null) {
    $q.notify({ color: 'warning', message: '먼저 우리 개를 등록해 주세요.', icon: 'pets', position: 'top' })
    return
  }
  matchingDogId.value = mate.dogId
  try {
    await matchesApi.create(dogs.currentDogId, mate.dogId)
    $q.notify({ color: 'positive', message: `${mate.name}에게 매칭을 신청했어요!`, icon: 'favorite', position: 'top' })
  } catch (e) {
    notifyError(e)
  } finally {
    matchingDogId.value = null
  }
}

function notifyError(e: unknown) {
  const message =
    e instanceof ApiError ? e.message : '요청 중 오류가 발생했습니다. 서버 연결을 확인하세요.'
  $q.notify({ color: 'negative', message, icon: 'error', position: 'top' })
}
</script>
