<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { accountApi } from '@/api/accountApi'
import { useDialog } from '@/composables/dialog'
import IconBtn from '@/components/ui/IconBtn.vue'

const dialog = useDialog()

const recurrings = ref([])
const wallets = ref([])
const categories = ref([])
const loading = ref(false)
const error = ref(null)

const formOpen = ref(false)
const editId = ref(null)
const form = reactive({
  title: '',
  type: 'EXPENSE',
  amount: null,
  category: '',
  memo: '',
  walletKind: '',
  walletId: '',
  toWalletKind: '',
  toWalletId: '',
  frequency: 'MONTHLY',
  dayOfMonth: 1,
  dayOfWeek: 1,
  monthOfYear: 1,
  startDate: '',
  endDate: '',
  active: true,
})
const submitting = ref(false)
const formError = ref(null)

const DOW = ['', '월', '화', '수', '목', '금', '토', '일']
const categoryOptions = computed(() => {
  const names = categories.value.filter((c) => c.type === form.type).map((c) => c.name)
  if (form.category && !names.includes(form.category)) names.unshift(form.category)
  return names
})
// 대분류로 그룹핑 (소분류=optgroup 옵션 / 자식없는 대분류=단독 옵션)
const categoryGroups = computed(() => {
  const list = categories.value.filter((c) => c.type === form.type)
  const groups = []
  if (form.category && !list.some((c) => c.name === form.category)) {
    groups.push({ key: '_cur', label: null, options: [form.category] })
  }
  for (const m of list.filter((c) => c.parentId == null)) {
    const children = list.filter((c) => c.parentId === m.id)
    if (children.length) groups.push({ key: 'g' + m.id, label: m.name, options: children.map((c) => c.name) })
    else groups.push({ key: 'i' + m.id, label: null, options: [m.name] })
  }
  return groups
})
// 계좌/카드 — 종류(계좌/카드)를 라디오로 고르고, 그 종류만 셀렉트로 노출
const WALLET_KINDS = [
  { value: 'BANK', label: '계좌' },
  { value: 'CASH', label: '현금' },
  { value: 'CARD', label: '카드' },
]
const walletsOfKind = computed(() => wallets.value.filter((w) => w.type === form.walletKind))
const toWalletsOfKind = computed(() => wallets.value.filter((w) => w.type === form.toWalletKind))
function walletKindOf(id) {
  const w = wallets.value.find((x) => x.id === id)
  return w ? w.type : ''
}
function onWalletKindChange() {
  form.walletId = ''
}
function onToWalletKindChange() {
  form.toWalletId = ''
}

function won(n) {
  return (n ?? 0).toLocaleString('ko-KR')
}
function typeLabel(t) {
  return t === 'INCOME' ? '수입' : t === 'TRANSFER' ? '이체' : '지출'
}
function freqLabel(r) {
  if (r.frequency === 'DAILY') return '매일'
  if (r.frequency === 'WEEKLY') return `매주 ${DOW[r.dayOfWeek] || ''}요일`
  if (r.frequency === 'MONTHLY') return `매월 ${r.dayOfMonth}일`
  return `매년 ${r.monthOfYear}/${r.dayOfMonth}`
}

// 결제일 정렬 키 (작을수록 먼저): 매일<매주(요일)<매월(일) / 매년(월·일)
function payKey(r) {
  if (r.frequency === 'DAILY') return 0
  if (r.frequency === 'WEEKLY') return r.dayOfWeek || 0
  if (r.frequency === 'YEARLY') return (r.monthOfYear || 0) * 100 + (r.dayOfMonth || 0)
  return r.dayOfMonth || 0 // MONTHLY
}

// 월간/년간 분리 → 카테고리별 그룹 → 결제일순 정렬 → 소계·합계 (활성 건만 합산, 중지 건은 표시만)
const PERIODS = [
  { key: 'MONTH', label: '월간 거래', freqs: ['DAILY', 'WEEKLY', 'MONTHLY'] },
  { key: 'YEAR', label: '년간 거래', freqs: ['YEARLY'] },
]
const grouped = computed(() =>
  PERIODS.map((p) => {
    const items = recurrings.value.filter((r) => p.freqs.includes(r.frequency))
    const catMap = {}
    for (const r of items) {
      const cat = r.type === 'TRANSFER' ? '이체' : r.category || '미분류'
      if (!catMap[cat]) catMap[cat] = { category: cat, items: [], subtotal: 0, minKey: Infinity }
      catMap[cat].items.push(r)
      catMap[cat].minKey = Math.min(catMap[cat].minKey, payKey(r))
      if (r.active) catMap[cat].subtotal += r.amount || 0
    }
    // 카테고리 안 항목은 결제일순, 카테고리도 가장 이른 결제일순으로 정렬
    const cats = Object.values(catMap)
    cats.forEach((c) => c.items.sort((a, b) => payKey(a) - payKey(b)))
    cats.sort((a, b) => a.minKey - b.minKey || a.category.localeCompare(b.category, 'ko'))
    const total = items.filter((r) => r.active).reduce((s, r) => s + (r.amount || 0), 0)
    return { ...p, cats, total, count: items.length }
  }).filter((g) => g.count > 0),
)
function todayStr() {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

async function load() {
  loading.value = true
  error.value = null
  try {
    const [recs, ws, cats] = await Promise.all([
      accountApi.recurrings(),
      accountApi.wallets(),
      accountApi.categories(),
    ])
    recurrings.value = recs
    wallets.value = ws
    categories.value = cats
  } catch (e) {
    error.value = e.response?.data?.message || '불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}

async function runNow() {
  try {
    const res = await accountApi.runRecurrings()
    alert(`${res.generated}건의 고정 지출가 반영되었습니다.`)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '반영에 실패했습니다.')
  }
}

function openCreate() {
  editId.value = null
  Object.assign(form, {
    title: '', type: 'EXPENSE', amount: null, category: '', memo: '',
    walletKind: '', walletId: '', toWalletKind: '', toWalletId: '', frequency: 'MONTHLY', dayOfMonth: 1, dayOfWeek: 1,
    monthOfYear: 1, startDate: todayStr(), endDate: '', active: true,
  })
  formError.value = null
  formOpen.value = true
}
function openEdit(r) {
  editId.value = r.id
  Object.assign(form, {
    title: r.title, type: r.type, amount: r.amount, category: r.category || '', memo: r.memo || '',
    walletKind: walletKindOf(r.walletId), walletId: r.walletId || '',
    toWalletKind: walletKindOf(r.toWalletId), toWalletId: r.toWalletId || '', frequency: r.frequency,
    dayOfMonth: r.dayOfMonth || 1, dayOfWeek: r.dayOfWeek || 1, monthOfYear: r.monthOfYear || 1,
    startDate: r.startDate, endDate: r.endDate || '', active: r.active,
  })
  formError.value = null
  formOpen.value = true
}

async function submit() {
  formError.value = null
  if (!form.title.trim()) {
    formError.value = '이름을 입력하세요.'
    return
  }
  if (!form.amount || form.amount <= 0) {
    formError.value = '금액을 입력하세요.'
    return
  }
  if (form.type === 'TRANSFER' && (!form.walletId || !form.toWalletId || form.walletId === form.toWalletId)) {
    formError.value = '이체는 서로 다른 출금/입금 계좌를 선택하세요.'
    return
  }
  if (!form.startDate) {
    formError.value = '시작일을 입력하세요.'
    return
  }
  submitting.value = true
  const payload = {
    title: form.title.trim(),
    type: form.type,
    amount: Number(form.amount),
    category: form.type === 'TRANSFER' ? null : form.category || null,
    memo: form.memo || null,
    walletId: form.walletId || null,
    toWalletId: form.type === 'TRANSFER' ? form.toWalletId || null : null,
    frequency: form.frequency,
    dayOfMonth: ['MONTHLY', 'YEARLY'].includes(form.frequency) ? Number(form.dayOfMonth) : null,
    dayOfWeek: form.frequency === 'WEEKLY' ? Number(form.dayOfWeek) : null,
    monthOfYear: form.frequency === 'YEARLY' ? Number(form.monthOfYear) : null,
    startDate: form.startDate,
    endDate: form.endDate || null,
    active: form.active,
  }
  try {
    if (editId.value) await accountApi.updateRecurring(editId.value, payload)
    else await accountApi.createRecurring(payload)
    formOpen.value = false
    await load()
  } catch (e) {
    formError.value = e.response?.data?.message || '저장에 실패했습니다.'
  } finally {
    submitting.value = false
  }
}

async function remove(r) {
  if (!(await dialog.confirm(`'${r.title}' 고정 지출를 삭제할까요?\n이미 생성된 내역은 유지됩니다.`, { title: '고정지출 삭제', danger: true }))) return
  try {
    await accountApi.removeRecurring(r.id)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '삭제에 실패했습니다.')
  }
}

onMounted(load)
</script>

<template>
  <section class="recur">
    <p class="hint">등록한 주기에 맞춰 가계부 진입 시 자동으로 <b>‘확인 필요’</b> 내역이 생성됩니다(중복 없이). 가계부에서 실제 결제·이체를 확인한 뒤 <b>‘확인’</b>을 눌러 확정하세요.</p>
    <div class="recur-actions">
      <IconBtn icon="refresh" title="지금 반영" @click="runNow" />
      <IconBtn icon="plus" title="고정 지출 추가" variant="primary" @click="openCreate" />
    </div>

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

    <div v-else-if="recurrings.length" class="recur-groups">
      <section v-for="g in grouped" :key="g.key" class="period-group">
        <div class="period-head">
          <h2>{{ g.label }}</h2>
          <span class="period-total">합계 {{ won(g.total) }}</span>
        </div>
        <div v-for="c in g.cats" :key="c.category" class="cat-group">
          <div class="cat-head">
            <span class="cat-name">{{ c.category }}</span>
            <span class="cat-subtotal">소계 {{ won(c.subtotal) }}</span>
          </div>
          <ul class="recur-list">
            <li v-for="r in c.items" :key="r.id" class="recur-row" :class="{ inactive: !r.active }">
              <div class="info">
                <div class="line1">
                  <span class="title">{{ r.title }}</span>
                  <span class="type-badge" :class="r.type.toLowerCase()">{{ typeLabel(r.type) }}</span>
                  <span v-if="!r.active" class="off">중지</span>
                </div>
                <div class="sub">{{ freqLabel(r) }} · {{ won(r.amount) }}</div>
                <div v-if="r.nextDate" class="next">다음 {{ r.nextDate }}</div>
              </div>
              <div class="actions">
                <IconBtn icon="edit" title="수정" size="sm" @click="openEdit(r)" />
                <IconBtn icon="trash" title="삭제" variant="danger" size="sm" @click="remove(r)" />
              </div>
            </li>
          </ul>
        </div>
      </section>
    </div>
    <p v-else-if="!loading" class="msg">등록된 고정 지출가 없습니다.</p>

    <!-- 추가/수정 모달 -->
    <Teleport to="body">
      <Transition name="fade">
        <div v-if="formOpen" class="modal-backdrop" @click.self="formOpen = false">
          <div class="modal" role="dialog" aria-modal="true">
            <button class="close" type="button" @click="formOpen = false">×</button>
            <h2>고정 지출 {{ editId ? '수정' : '추가' }}</h2>

            <form class="recur-form" @submit.prevent="submit">
              <label>이름<input v-model="form.title" type="text" placeholder="예: 월세, 급여" :disabled="submitting" /></label>
              <label>구분
                <select v-model="form.type" :disabled="submitting">
                  <option value="EXPENSE">지출</option>
                  <option value="INCOME">수입</option>
                  <option value="TRANSFER">이체</option>
                </select>
              </label>
              <label>금액<input v-model.number="form.amount" type="number" min="0" placeholder="원" :disabled="submitting" /></label>

              <div class="field">
                <div class="field-row">
                  <span class="field-label">{{ form.type === 'TRANSFER' ? '출금 계좌' : '계좌/카드' }}</span>
                  <div class="wallet-radios">
                    <label v-for="k in WALLET_KINDS" :key="k.value" class="radio">
                      <input type="radio" :value="k.value" v-model="form.walletKind" :disabled="submitting" @change="onWalletKindChange" />
                      {{ k.label }}
                    </label>
                  </div>
                </div>
                <select v-if="form.walletKind" v-model="form.walletId" :disabled="submitting">
                  <option value="">(선택)</option>
                  <option v-for="w in walletsOfKind" :key="w.id" :value="w.id">
                    {{ w.name }}{{ w.issuer ? ` (${w.issuer})` : '' }}
                  </option>
                </select>
              </div>
              <div v-if="form.type === 'TRANSFER'" class="field">
                <div class="field-row">
                  <span class="field-label">입금 계좌</span>
                  <div class="wallet-radios">
                    <label v-for="k in WALLET_KINDS" :key="k.value" class="radio">
                      <input type="radio" :value="k.value" v-model="form.toWalletKind" :disabled="submitting" @change="onToWalletKindChange" />
                      {{ k.label }}
                    </label>
                  </div>
                </div>
                <select v-if="form.toWalletKind" v-model="form.toWalletId" :disabled="submitting">
                  <option value="">(선택)</option>
                  <option v-for="w in toWalletsOfKind" :key="w.id" :value="w.id">
                    {{ w.name }}{{ w.issuer ? ` (${w.issuer})` : '' }}
                  </option>
                </select>
              </div>
              <label v-if="form.type !== 'TRANSFER'">분류
                <select v-model="form.category" :disabled="submitting">
                  <option value="">(선택)</option>
                  <template v-for="g in categoryGroups" :key="g.key">
                    <optgroup v-if="g.label" :label="g.label">
                      <option v-for="n in g.options" :key="n" :value="n">{{ n }}</option>
                    </optgroup>
                    <template v-else>
                      <option v-for="n in g.options" :key="n" :value="n">{{ n }}</option>
                    </template>
                  </template>
                </select>
              </label>
              <label>메모<input v-model="form.memo" type="text" placeholder="(선택)" :disabled="submitting" /></label>

              <label>주기
                <select v-model="form.frequency" :disabled="submitting">
                  <option value="DAILY">매일</option>
                  <option value="WEEKLY">매주</option>
                  <option value="MONTHLY">매월</option>
                  <option value="YEARLY">매년</option>
                </select>
              </label>
              <label v-if="form.frequency === 'WEEKLY'">요일
                <select v-model.number="form.dayOfWeek" :disabled="submitting">
                  <option v-for="d in 7" :key="d" :value="d">{{ DOW[d] }}</option>
                </select>
              </label>
              <label v-if="form.frequency === 'YEARLY'">월
                <input v-model.number="form.monthOfYear" type="number" min="1" max="12" :disabled="submitting" />
              </label>
              <label v-if="['MONTHLY', 'YEARLY'].includes(form.frequency)">일(날짜)
                <input v-model.number="form.dayOfMonth" type="number" min="1" max="31" :disabled="submitting" />
              </label>

              <label>시작일<input v-model="form.startDate" type="date" :disabled="submitting" /></label>
              <label>종료일(선택)<input v-model="form.endDate" type="date" :disabled="submitting" /></label>
              <label class="row"><input type="checkbox" v-model="form.active" :disabled="submitting" /> 활성</label>

              <p v-if="formError" class="msg error">{{ formError }}</p>

              <div class="buttons">
                <IconBtn icon="close" title="취소" @click="formOpen = false" />
                <IconBtn icon="save" :title="editId ? '수정' : '등록'" variant="primary" type="submit" :disabled="submitting" />
              </div>
            </form>
          </div>
        </div>
      </Transition>
    </Teleport>
  </section>
</template>

<style scoped>
.recur {
  max-width: 640px;
  margin: 0 auto;
}
.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 0.5rem;
}
.head-actions {
  display: flex;
  gap: 0.5rem;
}
h1 {
  font-size: 1.5rem;
}
.hint {
  font-size: 0.85rem;
  opacity: 0.7;
  margin: 0.5rem 0 1rem;
}
.recur-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-bottom: 1rem;
}
button {
  padding: 0.45rem 0.85rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
  cursor: pointer;
}
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
button.danger {
  border-color: #c0392b;
  color: #c0392b;
}
button.primary {
  border-color: hsla(160, 100%, 37%, 1);
  color: hsla(160, 100%, 37%, 1);
}
.recur-groups {
  margin-top: 0.5rem;
}
.period-group {
  margin-bottom: 1.5rem;
}
.period-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  padding-bottom: 0.3rem;
  border-bottom: 2px solid var(--color-border);
  margin-bottom: 0.5rem;
}
.period-head h2 {
  font-size: 1.1rem;
  font-weight: 700;
}
.period-total {
  font-size: 0.95rem;
  font-weight: 700;
  color: hsla(160, 100%, 37%, 1);
}
.cat-group {
  margin-bottom: 0.6rem;
}
.cat-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  padding: 0.25rem 0.1rem;
  background: var(--color-background-soft);
  border-radius: 4px;
}
.cat-name {
  font-size: 0.88rem;
  font-weight: 600;
}
.cat-subtotal {
  font-size: 0.82rem;
  font-weight: 600;
  opacity: 0.8;
}
.recur-list {
  list-style: none;
  padding-left: 0;
  margin: 0;
}
.recur-row {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 0.6rem;
  padding: 0.7rem 0;
  border-bottom: 1px solid var(--color-border);
}
.info {
  flex: 1;
  min-width: 0;
}
.recur-row.inactive {
  opacity: 0.55;
}
.line1 {
  display: flex;
  align-items: center;
  gap: 0.4rem;
}
.title {
  font-weight: 600;
}
.type-badge {
  font-size: 0.72rem;
  border: 1px solid var(--color-border);
  border-radius: 3px;
  padding: 0.05rem 0.35rem;
}
.type-badge.income {
  color: #2e7d32;
  border-color: #2e7d32;
}
.type-badge.expense {
  color: #c0392b;
  border-color: #c0392b;
}
.off {
  font-size: 0.72rem;
  opacity: 0.6;
}
.sub {
  font-size: 0.83rem;
  opacity: 0.75;
  margin-top: 0.15rem;
}
.next {
  font-size: 0.78rem;
  opacity: 0.6;
  margin-top: 0.1rem;
}
.actions {
  display: flex;
  gap: 0.4rem;
  flex-shrink: 0;
}
.actions button {
  padding: 0.2rem 0.55rem;
  font-size: 0.82rem;
}
.msg {
  margin: 0.75rem 0;
}
.msg.error {
  color: #c0392b;
}

/* 모달 */
.modal-backdrop {
  position: fixed;
  inset: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  padding: 1rem;
}
.modal {
  position: relative;
  width: 100%;
  max-width: 360px;
  max-height: 90vh;
  overflow-y: auto;
  padding: 1.75rem 1.5rem 1.5rem;
  background: var(--color-background);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
}
.modal .close {
  position: absolute;
  top: 0.5rem;
  right: 0.6rem;
  width: 2rem;
  height: 2rem;
  border: 0;
  background: transparent;
  font-size: 1.5rem;
  line-height: 1;
}
.modal h2 {
  margin-bottom: 1rem;
  font-size: 1.2rem;
  text-align: center;
}
.recur-form {
  display: flex;
  flex-direction: column;
  gap: 0.55rem;
}
.recur-form label {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  font-size: 0.85rem;
}
.recur-form label.row {
  flex-direction: row;
  align-items: center;
  gap: 0.4rem;
}
.recur-form input,
.recur-form select {
  padding: 0.5rem 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
}
.recur-form label.row input {
  padding: 0;
}
/* 계좌/카드 라디오 선택 */
.field {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}
.field-row {
  display: flex;
  align-items: center;
  gap: 0.9rem;
}
.field-label {
  font-size: 0.85rem;
  flex-shrink: 0;
}
.wallet-radios {
  display: flex;
  flex: 1;
  min-width: 0;
  flex-wrap: wrap;
  gap: 0.4rem 0.9rem;
  padding: 0.1rem 0;
}
.wallet-radios .radio {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.85rem;
  cursor: pointer;
}
.wallet-radios .radio input {
  padding: 0;
  width: auto;
  margin: 0;
}
.r-issuer {
  margin-left: 0.2rem;
  font-size: 0.72rem;
  opacity: 0.6;
}
.empty-hint {
  font-size: 0.78rem;
  opacity: 0.6;
}
.buttons {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 0.5rem;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.18s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
