<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'
import AppModal from '@/components/ui/AppModal.vue'
import CategoryPicker from '@/components/ui/CategoryPicker.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 TYPES = [
  { value: 'EXPENSE',  label: '지출',  cls: 'chip-expense' },
  { value: 'INCOME',   label: '수입',  cls: 'chip-income' },
  { value: 'TRANSFER', label: '이체',  cls: 'chip-transfer' },
]
const FREQS = [
  { value: 'DAILY',   label: '매일' },
  { value: 'WEEKLY',  label: '매주' },
  { value: 'MONTHLY', label: '매월' },
  { value: 'YEARLY',  label: '매년' },
]

// 계좌/카드 종류
const WALLET_KINDS = [
  { value: 'BANK',  label: '계좌' },
  { value: 'CASH',  label: '현금' },
  { value: 'CARD',  label: '카드' },
  { value: 'MINUS', 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 onTypeChange() { form.category = '' }

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
}

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>

    <!-- 추가/수정 모달 -->
    <AppModal v-model="formOpen" :title="`고정 지출 ${editId ? '수정' : '추가'}`">
      <form class="recur-form" @submit.prevent="submit">
        <label>이름<input v-model="form.title" type="text" placeholder="예: 월세, 급여" :disabled="submitting" /></label>

        <!-- 구분 배지 -->
        <div class="field">
          <span class="field-label">구분</span>
          <div class="type-chips">
            <button
              v-for="t in TYPES" :key="t.value"
              type="button" class="chip" :class="[t.cls, { active: form.type === t.value }]"
              :disabled="submitting"
              @click="form.type = t.value; onTypeChange()"
            >{{ t.label }}</button>
          </div>
        </div>

        <label>금액<input v-model.number="form.amount" type="number" min="0" placeholder="원" :disabled="submitting" /></label>

        <!-- 출금 계좌 종류 배지 -->
        <div class="field">
          <span class="field-label">{{ form.type === 'TRANSFER' ? '출금 계좌' : '계좌/카드' }}</span>
          <div class="wallet-chips">
            <button
              v-for="k in WALLET_KINDS" :key="k.value"
              type="button" class="chip" :class="{ active: form.walletKind === k.value }"
              :disabled="submitting"
              @click="form.walletKind = k.value; onWalletKindChange()"
            >{{ k.label }}</button>
          </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">
          <span class="field-label">입금 계좌</span>
          <div class="wallet-chips">
            <button
              v-for="k in WALLET_KINDS" :key="k.value"
              type="button" class="chip" :class="{ active: form.toWalletKind === k.value }"
              :disabled="submitting"
              @click="form.toWalletKind = k.value; onToWalletKindChange()"
            >{{ k.label }}</button>
          </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>

        <!-- 분류 — CategoryPicker (이체 제외) -->
        <div v-if="form.type !== 'TRANSFER'" class="field">
          <span class="field-label">분류</span>
          <CategoryPicker
            v-model="form.category"
            :type="form.type"
            :categories="categories"
            :disabled="submitting"
            @category-added="load()"
          />
        </div>

        <label>메모<input v-model="form.memo" type="text" placeholder="(선택)" :disabled="submitting" /></label>

        <!-- 주기 배지 -->
        <div class="field">
          <span class="field-label">주기</span>
          <div class="type-chips">
            <button
              v-for="f in FREQS" :key="f.value"
              type="button" class="chip" :class="{ active: form.frequency === f.value }"
              :disabled="submitting"
              @click="form.frequency = f.value"
            >{{ f.label }}</button>
          </div>
        </div>

        <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>
    </AppModal>
  </section>
</template>

<style scoped>
.recur {
  max-width: 640px;
  margin: 0 auto;
}
.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; }

/* 폼 */
.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-label { font-size: 0.82rem; opacity: 0.7; }
.type-chips,
.wallet-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
}
.chip {
  padding: 0.28rem 0.75rem;
  border: 1.5px solid var(--color-border);
  border-radius: 100px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-size: 0.82rem;
  font-weight: 500;
  cursor: pointer;
  line-height: 1.4;
  transition: border-color 0.12s, background 0.12s, color 0.12s;
}
.chip:disabled { opacity: 0.45; cursor: not-allowed; }
/* 기본 active (계좌/주기) */
.chip.active { border-color: hsla(160, 100%, 37%, 1); background: hsla(160, 100%, 37%, 1); color: #fff; }
/* 구분 배지 type별 색상 */
.chip-expense.active  { border-color: #c0392b; background: #c0392b; }
.chip-income.active   { border-color: #2e7d32; background: #2e7d32; }
.chip-transfer.active { border-color: #1565c0; background: #1565c0; }

.buttons {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 0.5rem;
}
</style>
