<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { accountApi } from '@/api/accountApi'
import { useDialog } from '@/composables/dialog'
import IconBtn from '@/components/ui/IconBtn.vue'
import CategoryPicker from '@/components/ui/CategoryPicker.vue'
import BottomSheet from '@/components/ui/BottomSheet.vue'

const dialog = useDialog()
const route = useRoute()
const router = useRouter()

const now = new Date()
const year = ref(now.getFullYear())
const month = ref(now.getMonth() + 1)

const statuses = ref([])
const budgetsRaw = ref([])
const loading = ref(false)
const error = ref(null)

// 폼 — 라우트(?budget) 바인딩으로 뒤로가기 시 닫힘(페이지 전환처럼)
const formOpen = ref(false)
function openForm() {
  formOpen.value = true
  if (route.query.budget == null) router.push({ query: { ...route.query, budget: '1' } })
}
function closeForm() {
  formOpen.value = false
  if (route.query.budget != null) router.back()
}
watch(() => route.query.budget, (v) => { if (v == null) formOpen.value = false })

const editId = ref(null)
const form = reactive({
  category: '',
  monthly: null,
})
const submitting = ref(false)
const formError = ref(null)
// 분류 선택 바텀시트 — 최종 분류 정해지면 닫힘
const catSheet = ref(false)
watch(() => form.category, (v) => { if (v) catSheet.value = false })

// 분류(지출) 드롭다운
const categories = ref([])
async function loadCategories() {
  try {
    categories.value = await accountApi.categories()
  } catch {
    categories.value = []
  }
}
const periodLabel = computed(() => `${year.value}년 ${String(month.value).padStart(2, '0')}월`)

function won(n) {
  return (n ?? 0).toLocaleString('ko-KR')
}
function ratio(s) {
  if (!s.monthlyBudget) return 0
  return Math.min(Math.round((s.spent / s.monthlyBudget) * 100), 999)
}
function barClass(s) {
  const r = s.monthlyBudget ? s.spent / s.monthlyBudget : 0
  return r >= 1 ? 'over' : r >= 0.8 ? 'warn' : 'ok'
}

// ===== 월 예상 수입 vs 총 예산 비교 =====
const expectedIncome = ref(null)
const incomeDraft = ref('')
async function loadIncome() {
  try {
    const r = await accountApi.expectedIncome({ year: year.value, month: month.value })
    expectedIncome.value = r.expectedIncome
    incomeDraft.value = r.expectedIncome ?? ''
  } catch {
    expectedIncome.value = null
    incomeDraft.value = ''
  }
}
async function saveIncome() {
  try {
    const v = incomeDraft.value === '' || incomeDraft.value == null ? 0 : Number(incomeDraft.value)
    const r = await accountApi.setExpectedIncome({ year: year.value, month: month.value, expectedIncome: v })
    expectedIncome.value = r.expectedIncome
  } catch (e) {
    alert(e.response?.data?.message || '저장에 실패했습니다.')
  }
}
const totalBudget = computed(() => statuses.value.reduce((s, x) => s + (x.monthlyBudget || 0), 0))
const incomeVal = computed(() => Number(expectedIncome.value) || 0)
const leftover = computed(() => incomeVal.value - totalBudget.value) // 여유(저축 가능액)
const budgetOfIncome = computed(() => (incomeVal.value > 0 ? Math.min(totalBudget.value / incomeVal.value, 1) : 0))

async function load() {
  loading.value = true
  error.value = null
  try {
    const params = { year: year.value, month: month.value }
    const [st, raw] = await Promise.all([accountApi.budgetStatus(params), accountApi.budgets(params)])
    statuses.value = st
    budgetsRaw.value = raw
  } catch (e) {
    error.value = e.response?.data?.message || '불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}

function prevMonth() {
  if (month.value === 1) {
    month.value = 12
    year.value -= 1
  } else month.value -= 1
  load()
  loadIncome()
}
function nextMonth() {
  if (month.value === 12) {
    month.value = 1
    year.value += 1
  } else month.value += 1
  load()
  loadIncome()
}

// ===== 월별 예산 복사 =====
const copying = ref(false)
const ym = (y, m) => `${y}.${String(m).padStart(2, '0')}`
async function copyToNextMonth() {
  if (copying.value || !budgetsRaw.value.length) return
  const to = month.value === 12 ? { y: year.value + 1, m: 1 } : { y: year.value, m: month.value + 1 }
  const ok = await dialog.confirm(
    `${ym(year.value, month.value)} 예산을 ${ym(to.y, to.m)}(다음 달)로 복사할까요?\n다음 달의 같은 분류 예산은 덮어씁니다.`,
    { title: '다음 달로 복사' },
  )
  if (!ok) return
  copying.value = true
  try {
    await accountApi.copyBudget({ fromYear: year.value, fromMonth: month.value, toYear: to.y, toMonth: to.m })
    await dialog.alert(`${ym(to.y, to.m)}로 예산을 복사했어요.`)
  } catch (e) {
    error.value = e.response?.data?.message || '복사에 실패했습니다.'
  } finally {
    copying.value = false
  }
}
async function copyFromPrevMonth() {
  if (copying.value) return
  const prev = month.value === 1 ? { y: year.value - 1, m: 12 } : { y: year.value, m: month.value - 1 }
  const ok = await dialog.confirm(
    `전월(${ym(prev.y, prev.m)}) 예산을 ${ym(year.value, month.value)}로 가져올까요?\n이 달의 같은 분류 예산은 덮어씁니다.`,
    { title: '전월 예산 복사' },
  )
  if (!ok) return
  copying.value = true
  try {
    await accountApi.copyBudget({ fromYear: prev.y, fromMonth: prev.m, toYear: year.value, toMonth: month.value })
    await load()
  } catch (e) {
    error.value = e.response?.data?.message || '복사에 실패했습니다.'
  } finally {
    copying.value = false
  }
}

function openCreate() {
  editId.value = null
  Object.assign(form, { category: '', monthly: null })
  formError.value = null
  openForm()
}
function openEdit(s) {
  const b = budgetsRaw.value.find((x) => x.id === s.id)
  if (!b) return
  editId.value = b.id
  Object.assign(form, { category: b.category, monthly: b.monthly })
  formError.value = null
  openForm()
}

async function submit() {
  formError.value = null
  if (!form.category.trim()) {
    formError.value = '카테고리를 입력하세요.'
    return
  }
  if (!form.monthly || form.monthly <= 0) {
    formError.value = '월 예산 금액을 입력하세요.'
    return
  }
  const payload = {
    category: form.category.trim(),
    fixed: false,
    daily: null,
    weekly: null,
    monthly: Number(form.monthly),
    yearly: null,
  }
  submitting.value = true
  try {
    if (editId.value) await accountApi.updateBudget(editId.value, payload)
    else await accountApi.createBudget(payload, { year: year.value, month: month.value })
    closeForm()
    await load()
  } catch (e) {
    formError.value = e.response?.data?.message || '저장에 실패했습니다.'
  } finally {
    submitting.value = false
  }
}

async function remove(s) {
  if (!(await dialog.confirm(`'${s.category}' 예산을 삭제할까요?`, { title: '예산 삭제', danger: true }))) return
  try {
    await accountApi.removeBudget(s.id)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '삭제에 실패했습니다.')
  }
}

onMounted(() => {
  load()
  loadCategories()
  loadIncome()
})
</script>

<template>
  <section class="budget">
    <template v-if="!formOpen">
    <div class="month-nav">
      <span class="mn-spacer"></span>
      <IconBtn icon="chevronLeft" title="이전 달" size="sm" @click="prevMonth" />
      <span class="period">{{ periodLabel }}</span>
      <IconBtn icon="chevronRight" title="다음 달" size="sm" @click="nextMonth" />
      <div class="mn-actions">
        <IconBtn icon="plus" title="예산 추가" variant="primary" @click="openCreate" />
      </div>
    </div>

    <!-- 월별 예산 복사 -->
    <div class="copy-actions">
      <button type="button" class="copy-btn" :disabled="copying" @click="copyFromPrevMonth">↤ 전월 예산 가져오기</button>
      <button type="button" class="copy-btn" :disabled="copying || !budgetsRaw.length" @click="copyToNextMonth">다음 달로 복사 ↦</button>
    </div>

    <!-- 월 예상 수입 vs 총 예산 -->
    <div class="income-panel">
      <div class="inc-input">
        <label>월 예상 수입</label>
        <input v-model.number="incomeDraft" type="number" min="0" placeholder="예상 수입(원)" @keyup.enter="saveIncome" />
        <IconBtn icon="check" title="저장" variant="primary" size="sm" @click="saveIncome" />
      </div>
      <div v-if="incomeVal > 0" class="inc-compare">
        <div class="inc-bar">
          <div class="inc-fill" :class="leftover < 0 ? 'over' : ''" :style="{ width: budgetOfIncome * 100 + '%' }"></div>
        </div>
        <div class="inc-nums">
          <span>수입 <b class="income">{{ won(incomeVal) }}</b></span>
          <span>예산 <b>{{ won(totalBudget) }}</b></span>
          <span :class="leftover < 0 ? 'expense' : 'income'">
            {{ leftover >= 0 ? '여유' : '초과' }} <b>{{ won(Math.abs(leftover)) }}</b>
          </span>
        </div>
      </div>
      <p v-else class="inc-hint">예상 수입을 입력하면 설정한 예산과 비교해 여유 금액을 보여줍니다.</p>
    </div>

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

    <ul v-else-if="statuses.length" class="status-list">
      <li v-for="s in statuses" :key="s.id" class="status-row">
        <div class="srow-top">
          <span class="cat">{{ s.category }}<span v-if="s.fixed" class="fixed-badge">고정</span></span>
          <span class="amounts">
            <span :class="s.remaining < 0 ? 'neg' : ''">{{ won(s.spent) }}</span>
            / {{ won(s.monthlyBudget) }}
          </span>
        </div>
        <div class="bar">
          <div class="bar-fill" :class="barClass(s)" :style="{ width: Math.min(ratio(s), 100) + '%' }"></div>
        </div>
        <div class="srow-bottom">
          <span class="ratio" :class="barClass(s)">{{ ratio(s) }}%</span>
          <span class="remain">
            {{ s.remaining >= 0 ? `잔여 ${won(s.remaining)}` : `초과 ${won(-s.remaining)}` }}
          </span>
          <span class="acts">
            <IconBtn icon="edit" title="수정" size="sm" @click="openEdit(s)" />
            <IconBtn icon="trash" title="삭제" variant="danger" size="sm" @click="remove(s)" />
          </span>
        </div>
      </li>
    </ul>
    <p v-else-if="!loading" class="msg">설정된 예산이 없습니다. "예산 추가"로 시작하세요.</p>
    </template>

    <!-- 예산 추가/수정 (인라인 페이지 — 헤더·하단바 유지, 뒤로가기로 닫힘) -->
    <div v-else class="budget-page">
      <header class="ep-head">
        <span class="ep-title">예산 {{ editId ? '수정' : '추가' }}</span>
      </header>
      <form class="budget-form" @submit.prevent="submit">
        <div class="field">
          <span class="field-label">카테고리</span>
          <button
            type="button" class="sheet-trigger" :class="{ empty: !form.category }"
            :disabled="submitting" @click="catSheet = true"
          >
            <span class="st-label">{{ form.category || '분류를 선택하세요' }}</span>
            <span class="st-caret">▾</span>
          </button>
        </div>
        <BottomSheet v-model="catSheet" title="분류 선택">
          <CategoryPicker
            v-model="form.category"
            type="EXPENSE"
            :categories="categories"
            :disabled="submitting"
            @category-added="loadCategories"
          />
        </BottomSheet>

        <label>월 예산<input v-model.number="form.monthly" type="number" min="0" placeholder="원" :disabled="submitting" /></label>
        <p class="note">설정한 월 예산 기준으로 이번 달 지출과 비교됩니다.</p>

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

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

<style scoped>
.budget {
  max-width: 640px;
  margin: 0 auto;
}
.budget-page .budget-form {
  max-width: 460px;
  margin: 0 auto;
}
.ep-head {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1.2rem;
}
.ep-title {
  font-size: 1.2rem;
  font-weight: 700;
}
.sheet-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
  width: 100%;
  padding: 0.55rem 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-size: 0.9rem;
  cursor: pointer;
  text-align: left;
}
.sheet-trigger:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.sheet-trigger.empty .st-label {
  opacity: 0.5;
}
.st-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.st-caret {
  opacity: 0.5;
  font-size: 0.8rem;
  flex-shrink: 0;
}
.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
}
h1 {
  font-size: 1.5rem;
}
.head-actions {
  display: flex;
  gap: 0.5rem;
}
button {
  padding: 0.45rem 0.9rem;
  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);
}
.month-nav {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  margin-bottom: 1.25rem;
}
.mn-spacer {
  flex: 1;
}
.mn-actions {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  gap: 0.4rem;
}
.period {
  font-size: 1.1rem;
  font-weight: 600;
  min-width: 8rem;
  text-align: center;
}
/* 예상 수입 vs 예산 */
.copy-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
  flex-wrap: wrap;
  margin: -0.4rem 0 1rem;
}
.copy-btn {
  padding: 0.4rem 0.8rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-size: 0.82rem;
  cursor: pointer;
}
.copy-btn:disabled {
  opacity: 0.45;
  cursor: default;
}
.income-panel {
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 0.8rem 1rem;
  margin-bottom: 1.25rem;
}
.inc-input {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.inc-input label {
  font-size: 0.85rem;
  font-weight: 600;
  white-space: nowrap;
}
.inc-input input {
  flex: 1;
  min-width: 0;
  padding: 0.45rem 0.6rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
}
.inc-compare {
  margin-top: 0.7rem;
}
.inc-bar {
  height: 8px;
  background: var(--color-background-mute);
  border-radius: 999px;
  overflow: hidden;
}
.inc-fill {
  height: 100%;
  border-radius: 999px;
  background: #2e7d32;
  transition: width 0.3s;
}
.inc-fill.over {
  background: #c0392b;
}
.inc-nums {
  display: flex;
  justify-content: space-between;
  gap: 0.5rem;
  margin-top: 0.4rem;
  font-size: 0.85rem;
}
.inc-nums .income {
  color: #2e7d32;
}
.inc-nums .expense {
  color: #c0392b;
}
.inc-hint {
  margin-top: 0.5rem;
  font-size: 0.8rem;
  opacity: 0.65;
}
.status-list {
  list-style: none;
  padding-left: 0;
  margin: 0;
}
.status-row {
  padding: 0.85rem 0;
  border-bottom: 1px solid var(--color-border);
}
.srow-top {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 0.4rem;
}
.cat {
  font-weight: 600;
}
.fixed-badge {
  margin-left: 0.4rem;
  font-size: 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: 3px;
  padding: 0.05rem 0.3rem;
  opacity: 0.8;
}
.amounts {
  font-size: 0.9rem;
}
.amounts .neg {
  color: #c0392b;
  font-weight: 600;
}
.bar {
  height: 8px;
  background: var(--color-background-mute);
  border-radius: 999px;
  overflow: hidden;
}
.bar-fill {
  height: 100%;
  border-radius: 999px;
  transition: width 0.3s;
}
.bar-fill.ok {
  background: #2e7d32;
}
.bar-fill.warn {
  background: #e67e22;
}
.bar-fill.over {
  background: #c0392b;
}
.srow-bottom {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-top: 0.35rem;
  font-size: 0.82rem;
}
.ratio.ok {
  color: #2e7d32;
}
.ratio.warn {
  color: #e67e22;
}
.ratio.over {
  color: #c0392b;
  font-weight: 700;
}
.remain {
  opacity: 0.8;
}
.acts {
  margin-left: auto;
  display: flex;
  gap: 0.35rem;
}
.acts button {
  padding: 0.15rem 0.5rem;
  font-size: 0.78rem;
}
.msg {
  margin: 1rem 0;
}
.msg.error {
  color: #c0392b;
}

.budget-form {
  display: flex;
  flex-direction: column;
  gap: 0.6rem;
}
.budget-form label {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  font-size: 0.85rem;
}
.budget-form input,
.budget-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);
}
/* 배지형 선택 */
.field {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}
.field-label {
  font-size: 0.82rem;
  opacity: 0.7;
}
.field-hint {
  font-size: 0.75rem;
  opacity: 0.7;
}
.chip-group {
  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; }
.chip.active {
  border-color: hsla(160, 100%, 37%, 1);
  background: hsla(160, 100%, 37%, 1);
  color: #fff;
}
.fixed-base {
  display: flex;
  gap: 0.5rem;
}
.fixed-base select {
  width: 5rem;
}
.fixed-base input {
  flex: 1;
}
.preview {
  font-size: 0.82rem;
  background: var(--color-background-soft);
  border-radius: 4px;
  padding: 0.5rem 0.6rem;
}
.note {
  font-size: 0.78rem;
  opacity: 0.6;
}
.buttons {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 0.5rem;
}
/* 1회성 예산 */
.onetime-section {
  margin-top: 2rem;
  border-top: 2px solid var(--color-border);
  padding-top: 1.25rem;
}
.onetime-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 1rem;
}
.onetime-title {
  font-size: 1rem;
  font-weight: 700;
}
.onetime-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.onetime-row {
  padding: 0.85rem 0;
  border-bottom: 1px solid var(--color-border);
}
.ot-top {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  margin-bottom: 0.4rem;
}
.ot-name {
  font-weight: 600;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ot-status {
  font-size: 0.7rem;
  border-radius: 3px;
  padding: 0.05rem 0.35rem;
  border: 1px solid;
  white-space: nowrap;
}
.ot-status.active  { color: #2e7d32; border-color: #2e7d32; }
.ot-status.upcoming { color: #1565c0; border-color: #1565c0; }
.ot-status.ended   { opacity: 0.5; }
.ot-amounts {
  font-size: 0.9rem;
  white-space: nowrap;
}
.ot-amounts .neg { color: #c0392b; font-weight: 600; }
.ot-sep { opacity: 0.5; margin: 0 0.2rem; }
.ot-bottom {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  margin-top: 0.35rem;
  font-size: 0.8rem;
  flex-wrap: wrap;
}
.ot-date { opacity: 0.65; }
.ot-cat {
  background: var(--color-background-mute);
  border-radius: 3px;
  padding: 0.05rem 0.35rem;
  font-size: 0.75rem;
}
.ot-remain { opacity: 0.85; }
.ot-remain.neg { color: #c0392b; opacity: 1; }
.ot-empty { opacity: 0.6; }

/* 날짜 범위 입력 */
.date-range {
  display: flex;
  align-items: flex-end;
  gap: 0.4rem;
}
.date-range label {
  flex: 1;
}
.range-sep {
  padding-bottom: 0.55rem;
  opacity: 0.6;
  font-size: 0.9rem;
}
</style>
