<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { accountApi } from '@/api/accountApi'
import IconBtn from '@/components/ui/IconBtn.vue'

const route = useRoute()
const router = useRouter()
const walletId = Number(route.params.id)

const wallet = ref(null)
const entries = ref([])
const loading = ref(false)
const error = ref(null)
const month = ref('') // YYYY-MM

const TYPE_LABEL = {
  BANK: '은행계좌',
  CASH: '현금',
  CARD: '신용/체크카드',
  LOAN: '대출',
  MINUS: '마이너스통장',
  INVEST: '투자',
}
const isLiability = (t) => t === 'CARD' || t === 'LOAN' || t === 'MINUS'

function won(n) {
  return (n ?? 0).toLocaleString('ko-KR')
}
function currentYm() {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
}
function ymLabel(ym) {
  return ym ? ym.replace('-', '.') : ''
}
function cardTypeLabel(v) {
  return v === 'CHECK' ? '체크' : v === 'CREDIT' ? '신용' : ''
}
function loanMethodLabel(v) {
  return v === 'EQUAL_PAYMENT' ? '원리금균등' : v === 'EQUAL_PRINCIPAL' ? '원금균등' : v === 'BULLET' ? '만기일시' : ''
}

// 이 계좌 기준 증감(+입금/상환, -지출/출금)
function effectAmount(e) {
  if (e.type === 'TRANSFER') return e.toWalletId === walletId ? e.amount : -e.amount
  return e.type === 'INCOME' ? e.amount : -e.amount
}
function entryDesc(e) {
  const m = e.memo ? ` · ${e.memo}` : ''
  const w = wallet.value
  if (e.type === 'TRANSFER') {
    if (e.toWalletId === walletId) {
      const inLabel = w && isLiability(w.type) ? '상환/납부' : '입금'
      return `${inLabel} ← ${e.walletName || '계좌'}${m}`
    }
    return `이체 → ${e.toWalletName || '계좌'}${m}`
  }
  if (e.type === 'INCOME') return `수입${e.category ? ' · ' + e.category : ''}${m}`
  return `${e.category || '지출'}${m}`
}
function entryDate(v) {
  if (!v) return '-'
  const d = new Date(v)
  return Number.isNaN(d.getTime())
    ? v
    : `${String(d.getMonth() + 1).padStart(2, '0')}.${String(d.getDate()).padStart(2, '0')}`
}

const monthListArr = computed(() => {
  const set = new Set(entries.value.map((e) => (e.entryDate || '').slice(0, 7)).filter(Boolean))
  return [...set].sort()
})
const monthEntries = computed(() =>
  entries.value.filter((e) => (e.entryDate || '').slice(0, 7) === month.value),
)
const monthSum = computed(() => monthEntries.value.reduce((s, e) => s + effectAmount(e), 0))
const canPrev = computed(() => monthListArr.value.indexOf(month.value) > 0)
const canNext = computed(() => {
  const i = monthListArr.value.indexOf(month.value)
  return i >= 0 && i < monthListArr.value.length - 1
})
function shiftMonth(delta) {
  const ms = monthListArr.value
  if (!ms.length) return
  const i = ms.indexOf(month.value)
  const j = Math.min(ms.length - 1, Math.max(0, (i === -1 ? ms.length - 1 : i) + delta))
  month.value = ms[j]
}

async function load() {
  loading.value = true
  error.value = null
  try {
    const ws = await accountApi.wallets()
    wallet.value = ws.find((w) => w.id === walletId) || null
    if (!wallet.value) {
      error.value = '계좌를 찾을 수 없습니다.'
      return
    }
    if (wallet.value.type !== 'INVEST') {
      entries.value = await accountApi.walletEntries(walletId)
      const ms = monthListArr.value
      month.value = ms.length ? ms[ms.length - 1] : currentYm()
    }
  } catch (e) {
    error.value = e.response?.data?.message || '불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}
onMounted(load)
</script>

<template>
  <section class="wdetail">
    <header class="wd-head">
      <IconBtn icon="back" title="뒤로" @click="router.back()" />
      <span class="wd-title">{{ wallet?.name || '계좌' }}</span>
    </header>

    <p v-if="error" class="msg error">{{ error }}</p>
    <p v-else-if="loading" class="msg">불러오는 중...</p>

    <template v-else-if="wallet">
      <!-- 계좌 요약 카드 -->
      <div class="wd-summary">
        <div class="wd-sum-top">
          <span class="wd-type">{{ TYPE_LABEL[wallet.type] }}</span>
          <span v-if="wallet.type === 'CARD' && wallet.cardType" class="wd-badge">{{ cardTypeLabel(wallet.cardType) }}</span>
        </div>
        <div class="wd-figure" :class="{ neg: wallet.type === 'INVEST' ? false : wallet.balance < 0 }">
          <template v-if="wallet.type === 'INVEST'">투자금 {{ won(wallet.investedAmount) }}</template>
          <template v-else>{{ won(wallet.balance) }}</template>
        </div>
        <div class="wd-meta">
          <span v-if="wallet.issuer">{{ wallet.issuer }}</span>
          <span v-if="wallet.type === 'LOAN' && wallet.loanRate">
            · {{ wallet.loanRate }}%<template v-if="wallet.loanMethod"> / {{ loanMethodLabel(wallet.loanMethod) }}</template>
          </span>
        </div>
      </div>

      <!-- 투자: 내역 대신 안내 -->
      <div v-if="wallet.type === 'INVEST'" class="wd-invest-note">
        <p>투자금(투입원금)을 표시합니다. 금액 변경은 계좌 관리에서 <b>수정</b>하세요.</p>
      </div>

      <!-- 그 외: 월별 내역 -->
      <template v-else>
        <div v-if="monthListArr.length" class="wd-month-nav">
          <button type="button" class="mn-btn" :disabled="!canPrev" aria-label="이전 달" @click="shiftMonth(-1)">◀</button>
          <span class="mn-label">{{ ymLabel(month) }}</span>
          <button type="button" class="mn-btn" :disabled="!canNext" aria-label="다음 달" @click="shiftMonth(1)">▶</button>
          <span class="mn-sum" :class="monthSum < 0 ? 'neg' : 'pos'">
            합계 {{ monthSum >= 0 ? '+' : '' }}{{ won(monthSum) }}
          </span>
        </div>

        <ul v-if="monthEntries.length" class="wd-list">
          <li v-for="e in monthEntries" :key="e.id" class="wd-row">
            <span class="d-date">{{ entryDate(e.entryDate) }}</span>
            <span class="d-desc">{{ entryDesc(e) }}</span>
            <span class="d-amount" :class="effectAmount(e) < 0 ? 'neg' : 'pos'">
              {{ effectAmount(e) >= 0 ? '+' : '' }}{{ won(effectAmount(e)) }}
            </span>
          </li>
        </ul>
        <p v-else-if="monthListArr.length" class="msg">이 달 내역이 없습니다.</p>
        <p v-else class="msg">연관 내역이 없습니다.</p>
      </template>
    </template>
  </section>
</template>

<style scoped>
.wdetail {
  max-width: 760px;
  margin: 0 auto;
}
.wd-head {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
}
.wd-title {
  font-size: 1.2rem;
  font-weight: 700;
}
.msg {
  margin: 0.75rem 0;
  opacity: 0.8;
}
.msg.error {
  color: #c0392b;
}
.wd-summary {
  border: 1px solid var(--color-border);
  border-radius: 12px;
  padding: 1rem 1.1rem;
  margin-bottom: 1rem;
}
.wd-sum-top {
  display: flex;
  align-items: center;
  gap: 0.4rem;
}
.wd-type {
  font-size: 0.85rem;
  opacity: 0.7;
}
.wd-badge {
  font-size: 0.72rem;
  padding: 0.05rem 0.4rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
}
.wd-figure {
  font-size: 1.6rem;
  font-weight: 800;
  margin-top: 0.25rem;
}
.wd-figure.neg {
  color: #c0392b;
}
.wd-meta {
  margin-top: 0.3rem;
  font-size: 0.85rem;
  opacity: 0.65;
}
.wd-invest-note {
  font-size: 0.9rem;
  opacity: 0.75;
  line-height: 1.5;
}
.wd-month-nav {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0.5rem 0 0.75rem;
}
.mn-btn {
  border: 1px solid var(--color-border);
  background: var(--color-background-soft);
  border-radius: 6px;
  width: 2rem;
  height: 2rem;
  cursor: pointer;
  color: var(--color-text);
}
.mn-btn:disabled {
  opacity: 0.4;
  cursor: default;
}
.mn-label {
  font-weight: 700;
}
.mn-sum {
  margin-left: auto;
  font-weight: 700;
}
.mn-sum.neg,
.d-amount.neg {
  color: #c0392b;
}
.mn-sum.pos,
.d-amount.pos {
  color: #2e7d32;
}
.wd-list {
  list-style: none;
  margin: 0;
  padding: 0;
}
.wd-row {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  padding: 0.6rem 0.2rem;
  border-bottom: 1px solid var(--color-border);
}
.d-date {
  flex: 0 0 auto;
  font-size: 0.82rem;
  opacity: 0.6;
  width: 3rem;
}
.d-desc {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 0.9rem;
}
.d-amount {
  flex: 0 0 auto;
  font-weight: 600;
  font-size: 0.9rem;
}
</style>
