<template>
  <q-page class="q-pa-md">
    <!-- 회원 + 구독 티어 (실데이터) -->
    <q-card flat bordered class="q-mb-md">
      <q-item>
        <q-item-section avatar>
          <q-avatar color="primary" text-color="white" icon="person" />
        </q-item-section>
        <q-item-section>
          <q-item-label class="text-weight-medium">{{ auth.member?.nickname }}</q-item-label>
          <q-item-label caption>{{ auth.member?.email }}</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-chip dense color="primary" text-color="white" icon="bolt">
            {{ auth.member?.subscriptionTier }}
          </q-chip>
        </q-item-section>
      </q-item>
    </q-card>

    <!-- 강아지 없을 때 -->
    <q-card v-if="!dogs.myDogs.length" flat bordered class="q-pa-lg text-center text-grey-6">
      <q-icon name="pets" size="40px" color="secondary" />
      <div class="q-mt-sm q-mb-md">아직 등록된 강아지가 없어요.</div>
      <q-btn color="primary" unelevated icon="add" label="우리 강아지 등록" @click="openCreate" />
    </q-card>

    <template v-else>
      <!-- 강아지 선택 (여러 마리) -->
      <div class="row items-center q-mb-sm">
        <div class="text-subtitle1 text-weight-bold">우리 강아지</div>
        <q-space />
        <q-btn dense flat color="primary" icon="add" label="추가" @click="openCreate" />
      </div>

      <div v-if="dogs.myDogs.length > 1" class="row q-gutter-sm q-mb-md">
        <q-chip
          v-for="d in dogs.myDogs"
          :key="d.id"
          clickable
          :color="d.id === dogs.currentDogId ? 'primary' : 'grey-3'"
          :text-color="d.id === dogs.currentDogId ? 'white' : 'grey-8'"
          @click="dogs.currentDogId = d.id"
        >
          {{ d.name }}
        </q-chip>
      </div>

      <!-- 대표 강아지 프로필 -->
      <q-card v-if="current" flat bordered class="q-mb-md">
        <q-card-section class="row items-center">
          <q-avatar size="64px" color="secondary" text-color="accent" icon="pets" />
          <div class="q-ml-md">
            <div class="text-h6">{{ current.name }}</div>
            <div class="text-caption text-grey-7">
              {{ current.breed || '견종 미상' }}<span v-if="current.size"> · {{ sizeLabel(current.size) }}</span
              ><span v-if="current.gender"> · {{ genderLabel(current.gender) }}</span
              ><span v-if="dogAge(current.birthDate)"> · {{ dogAge(current.birthDate) }}</span>
            </div>
            <div v-if="hoodScore" class="text-caption row items-center no-wrap q-mt-xs">
              <q-icon name="groups" size="14px" color="teal" class="q-mr-xs" />
              <span class="text-weight-medium text-teal-8">동네 찰떡지수 {{ hoodScore.percent }}%</span>
              <span class="text-grey-6 q-ml-xs">({{ hoodScore.label }})</span>
            </div>
          </div>
          <q-space />
          <q-btn dense flat round color="grey-6" icon="delete_outline" @click="onDelete" />
        </q-card-section>
      </q-card>

      <!-- 댕비티아이 성향 태그 편집 -->
      <div class="text-subtitle1 text-weight-bold q-mb-sm">댕비티아이 · 성향 태그</div>
      <div class="row q-gutter-sm q-mb-md">
        <q-chip
          v-for="tag in dogs.traitTags"
          :key="tag.id"
          clickable
          :color="selected.has(tag.id) ? 'primary' : 'grey-3'"
          :text-color="selected.has(tag.id) ? 'white' : 'grey-7'"
          @click="toggle(tag.id)"
        >
          {{ tag.label }}
        </q-chip>
      </div>

      <!-- AI 추천 조건 (원하는 메이트 조건 → AI 분석 반영) -->
      <div class="text-subtitle1 text-weight-bold q-mb-xs row items-center">
        <q-icon name="auto_awesome" color="primary" size="20px" class="q-mr-xs" />AI 추천 조건
      </div>
      <div class="text-caption text-grey-6 q-mb-sm">
        AI 추천 찰떡 메이트를 찾을 때 이 조건을 반영해요
      </div>
      <div class="q-mb-sm">
        <div class="text-caption text-grey-7 q-mb-xs">선호 성별</div>
        <q-btn-toggle
          v-model="prefGender"
          spread dense unelevated no-caps size="sm"
          toggle-color="primary" color="grey-3" text-color="grey-8"
          :options="prefGenderOptions"
        />
      </div>
      <div class="q-mb-sm">
        <div class="text-caption text-grey-7 q-mb-xs">선호 연령</div>
        <q-btn-toggle
          v-model="prefAge"
          spread dense unelevated no-caps size="sm"
          toggle-color="primary" color="grey-3" text-color="grey-8"
          :options="prefAgeOptions"
        />
      </div>
      <div class="q-mb-md">
        <div class="text-caption text-grey-7 q-mb-xs">선호 중성화</div>
        <q-btn-toggle
          v-model="prefNeutered"
          spread dense unelevated no-caps size="sm"
          toggle-color="primary" color="grey-3" text-color="grey-8"
          :options="prefNeuteredOptions"
        />
      </div>

      <q-btn
        color="primary"
        unelevated
        icon="save"
        label="저장"
        :loading="saving"
        :disable="!dirty"
        @click="saveTraits"
      />
    </template>

    <!-- 강아지 등록 다이얼로그 -->
    <q-dialog v-model="createOpen">
      <q-card style="min-width: 300px">
        <q-card-section class="text-subtitle1 text-weight-bold">우리 강아지 등록</q-card-section>
        <q-card-section class="q-gutter-sm">
          <q-input v-model="form.name" label="이름 *" dense outlined />
          <q-input v-model="form.breed" label="견종" dense outlined />

          <div>
            <div class="text-caption text-grey-7 q-mb-xs">크기</div>
            <q-btn-toggle
              v-model="form.size"
              spread
              unelevated
              no-caps
              toggle-color="primary"
              color="grey-3"
              text-color="grey-8"
              :options="sizeOptions"
            />
          </div>

          <div>
            <div class="text-caption text-grey-7 q-mb-xs">성별</div>
            <q-btn-toggle
              v-model="form.gender"
              spread
              unelevated
              no-caps
              toggle-color="primary"
              color="grey-3"
              text-color="grey-8"
              :options="[
                { label: '남아', value: 'MALE' },
                { label: '여아', value: 'FEMALE' },
              ]"
            />
          </div>

          <div>
            <div class="text-caption text-grey-7 q-mb-xs">
              연령<span v-if="ageText" class="text-primary q-ml-xs">· {{ ageText }}</span>
            </div>
            <div class="row q-col-gutter-sm">
              <q-select
                v-model="form.birthYear"
                :options="yearOptions"
                label="출생 연도"
                class="col"
                dense
                outlined
                emit-value
                map-options
              />
              <q-select
                v-model="form.birthMonth"
                :options="monthOptions"
                label="월"
                class="col-5"
                dense
                outlined
                emit-value
                map-options
              />
            </div>
          </div>

          <div>
            <div class="text-caption text-grey-7 q-mb-xs">중성화 여부 <span class="text-negative">*</span></div>
            <q-btn-toggle
              v-model="form.neutered"
              spread
              unelevated
              no-caps
              toggle-color="primary"
              color="grey-3"
              text-color="grey-8"
              :options="[
                { label: '중성화 완료', value: true },
                { label: '안 함', value: false },
              ]"
            />
          </div>

          <!-- AI 추천 조건: 원하는 메이트 조건 (AI 분석에 반영) -->
          <q-separator class="q-my-xs" />
          <div class="text-subtitle2 row items-center">
            <q-icon name="auto_awesome" color="primary" size="18px" class="q-mr-xs" />AI 추천 조건
          </div>
          <div class="text-caption text-grey-6 q-mb-xs">이런 친구를 찾아달라고 AI에게 알려줘요</div>
          <div>
            <div class="text-caption text-grey-7 q-mb-xs">선호 성별</div>
            <q-btn-toggle
              v-model="form.prefGender"
              spread dense unelevated no-caps size="sm"
              toggle-color="primary" color="grey-3" text-color="grey-8"
              :options="prefGenderOptions"
            />
          </div>
          <div>
            <div class="text-caption text-grey-7 q-mb-xs">선호 연령</div>
            <q-btn-toggle
              v-model="form.prefAge"
              spread dense unelevated no-caps size="sm"
              toggle-color="primary" color="grey-3" text-color="grey-8"
              :options="prefAgeOptions"
            />
          </div>
          <div>
            <div class="text-caption text-grey-7 q-mb-xs">선호 중성화</div>
            <q-btn-toggle
              v-model="form.prefNeutered"
              spread dense unelevated no-caps size="sm"
              toggle-color="primary" color="grey-3" text-color="grey-8"
              :options="prefNeuteredOptions"
            />
          </div>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="취소" v-close-popup />
          <q-btn
            color="primary"
            unelevated
            label="등록"
            :loading="creating"
            :disable="!form.name || form.neutered === null"
            @click="onCreate"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useQuasar } from 'quasar'
import { useAuthStore } from '@/stores/auth'
import { useDogsStore } from '@/stores/dogs'
import { affinityApi, type NeighborhoodScore } from '@/api/affinity'
import { ApiError } from '@/api/http'

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

const current = computed(() => dogs.currentDog)

// 내 강아지 동네 찰떡지수 (전체 노출 지표)
const hoodScore = ref<NeighborhoodScore | null>(null)
watch(
  () => current.value?.id,
  async (id) => {
    hoodScore.value = null
    if (id == null) return
    try {
      hoodScore.value = await affinityApi.neighborhood(id)
    } catch {
      hoodScore.value = null
    }
  },
  { immediate: true },
)
const selected = ref<Set<number>>(new Set())
const saving = ref(false)
const createOpen = ref(false)
const creating = ref(false)

const sizeOptions = [
  { label: '소형견', value: 'SMALL' },
  { label: '중형견', value: 'MEDIUM' },
  { label: '대형견', value: 'LARGE' },
]

// AI 추천 조건 선택지 (ANY = 상관없음)
const prefGenderOptions = [
  { label: '상관없음', value: 'ANY' },
  { label: '남아', value: 'MALE' },
  { label: '여아', value: 'FEMALE' },
]
const prefAgeOptions = [
  { label: '상관없음', value: 'ANY' },
  { label: '퍼피', value: 'PUPPY' },
  { label: '성견', value: 'ADULT' },
  { label: '노령', value: 'SENIOR' },
]
const prefNeuteredOptions = [
  { label: '상관없음', value: 'ANY' },
  { label: '완료', value: 'YES' },
  { label: '안 함', value: 'NO' },
]

const form = reactive<{
  name: string
  breed: string
  size: string | null
  gender: string | null
  birthYear: number | null
  birthMonth: number | null
  neutered: boolean | null
  prefGender: string
  prefAge: string
  prefNeutered: string
}>({
  name: '',
  breed: '',
  size: null,
  gender: null,
  birthYear: null,
  birthMonth: null,
  neutered: null,
  prefGender: 'ANY',
  prefAge: 'ANY',
  prefNeutered: 'ANY',
})

// 프로필 화면에서 편집하는 현재 강아지의 AI 추천 조건
const prefGender = ref('ANY')
const prefAge = ref('ANY')
const prefNeutered = ref('ANY')

// 출생 연도(올해 ~ 20년 전) / 월 선택지
const thisYear = new Date().getFullYear()
const yearOptions = Array.from({ length: 21 }, (_, i) => {
  const y = thisYear - i
  return { label: `${y}년`, value: y }
})
const monthOptions = Array.from({ length: 12 }, (_, i) => ({ label: `${i + 1}월`, value: i + 1 }))

// 선택한 출생 연·월 → 연령 텍스트 (예: 2살 3개월)
const ageText = computed(() => {
  if (form.birthYear == null || form.birthMonth == null) return ''
  return ageFromBirth(form.birthYear, form.birthMonth)
})

onMounted(async () => {
  try {
    await Promise.all([dogs.loadMyDogs(), dogs.loadTraitTags()])
  } catch (e) {
    notifyError(e)
  }
})

// 대표 강아지가 바뀌면 선택된 성향 + AI 추천 조건 동기화
watch(
  current,
  (d) => {
    selected.value = new Set(d?.traits.map((t) => t.id) ?? [])
    prefGender.value = d?.prefGender ?? 'ANY'
    prefAge.value = d?.prefAge ?? 'ANY'
    prefNeutered.value = d?.prefNeutered ?? 'ANY'
  },
  { immediate: true },
)

// 변경 감지(저장 버튼 활성화) — 성향 태그 또는 AI 추천 조건 변경 시
const dirty = computed(() => {
  const orig = new Set(current.value?.traits.map((t) => t.id) ?? [])
  if (orig.size !== selected.value.size) return true
  for (const id of selected.value) if (!orig.has(id)) return true
  if (prefGender.value !== (current.value?.prefGender ?? 'ANY')) return true
  if (prefAge.value !== (current.value?.prefAge ?? 'ANY')) return true
  if (prefNeutered.value !== (current.value?.prefNeutered ?? 'ANY')) return true
  return false
})

function toggle(id: number) {
  const next = new Set(selected.value)
  next.has(id) ? next.delete(id) : next.add(id)
  selected.value = next
}

function sizeLabel(size: string) {
  return sizeOptions.find((o) => o.value === size)?.label ?? size
}

function genderLabel(gender: string) {
  return gender === 'MALE' ? '남아' : gender === 'FEMALE' ? '여아' : gender
}

/** birthDate(YYYY-MM-DD) → 연령 텍스트. 없으면 빈 문자열. */
function dogAge(birthDate: string | null): string {
  if (!birthDate) return ''
  const [y, m] = birthDate.split('-').map(Number)
  if (!y || !m) return ''
  return ageFromBirth(y, m)
}

async function saveTraits() {
  if (!current.value) return
  saving.value = true
  try {
    await dogs.updateDog(current.value.id, {
      name: current.value.name,
      breed: current.value.breed,
      birthDate: current.value.birthDate,
      size: current.value.size,
      gender: current.value.gender,
      neutered: current.value.neutered,
      imageUrl: current.value.imageUrl,
      prefGender: prefGender.value,
      prefAge: prefAge.value,
      prefNeutered: prefNeutered.value,
      traitIds: [...selected.value],
    })
    $q.notify({ color: 'primary', message: '저장했어요.', icon: 'check', position: 'top' })
  } catch (e) {
    notifyError(e)
  } finally {
    saving.value = false
  }
}

function openCreate() {
  form.name = ''
  form.breed = ''
  form.size = null
  form.gender = null
  form.birthYear = null
  form.birthMonth = null
  form.neutered = null
  form.prefGender = 'ANY'
  form.prefAge = 'ANY'
  form.prefNeutered = 'ANY'
  createOpen.value = true
}

async function onCreate() {
  if (form.neutered === null) return
  creating.value = true
  try {
    // 출생 연·월 → birthDate (해당 월 1일). 둘 다 선택해야 저장.
    const birthDate =
      form.birthYear != null && form.birthMonth != null
        ? `${form.birthYear}-${String(form.birthMonth).padStart(2, '0')}-01`
        : null
    await dogs.createDog({
      name: form.name,
      breed: form.breed || null,
      size: form.size,
      gender: form.gender,
      birthDate,
      neutered: form.neutered,
      prefGender: form.prefGender,
      prefAge: form.prefAge,
      prefNeutered: form.prefNeutered,
    })
    createOpen.value = false
    $q.notify({ color: 'primary', message: `${form.name} 등록 완료!`, icon: 'pets', position: 'top' })
  } catch (e) {
    notifyError(e)
  } finally {
    creating.value = false
  }
}

/** 출생 연·월로 연령 텍스트 계산 (예: 2살 3개월 / 5개월). */
function ageFromBirth(year: number, month: number): string {
  const now = new Date()
  let months = (now.getFullYear() - year) * 12 + (now.getMonth() + 1 - month)
  if (months < 0) months = 0
  const y = Math.floor(months / 12)
  const mo = months % 12
  if (y <= 0) return `${mo}개월`
  return mo > 0 ? `${y}살 ${mo}개월` : `${y}살`
}

async function onDelete() {
  if (!current.value) return
  $q.dialog({
    title: '삭제',
    message: `${current.value.name}을(를) 삭제할까요?`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    try {
      await dogs.removeDog(current.value!.id)
      $q.notify({ color: 'grey-8', message: '삭제되었습니다.', position: 'top' })
    } catch (e) {
      notifyError(e)
    }
  })
}

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