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

const route = useRoute()
const router = useRouter()
const editId = route.params.id ? Number(route.params.id) : null
const isEdit = editId != null

const wallets = ref([])
const categories = ref([])
const loading = ref(false)
const submitting = ref(false)
const formError = ref(null)
const catSheet = ref(false)

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,
})
// 분류가 최종 선택(비어있지 않은 값)되면 시트 닫기
watch(() => form.category, (v) => { if (v) catSheet.value = false })

const TYPES = [
  { value: 'EXPENSE', label: '지출', cls: 'chip-expense' },
  { value: 'INCOME', label: '수입', cls: 'chip-income' },
  { value: 'TRANSFER', label: '이체', cls: 'chip-transfer' },
]
const FREQS = [
  { value: 'MONTHLY', label: '매월' },
  { value: 'YEARLY', label: '매년' },
]
const WALLET_KINDS = [
  { value: 'BANK', label: '계좌' },
  { value: 'CASH', label: '현금' },
  { value: 'CARD', label: '카드' },
  { value: 'MINUS', label: '마이너스' },
]
const fromWalletKinds = computed(() =>
  WALLET_KINDS.filter((k) => k.value !== 'CARD' || form.type === 'EXPENSE'),
)
const toWalletKinds = computed(() => WALLET_KINDS.filter((k) => k.value !== 'CARD'))
// 구분에 따라 선택 가능한 출금/입금 계좌 목록(계좌 종류로 필터)
const fromWallets = computed(() =>
  wallets.value.filter((w) => fromWalletKinds.value.some((k) => k.value === w.type)),
)
const toWallets = computed(() =>
  wallets.value.filter((w) => toWalletKinds.value.some((k) => k.value === w.type)),
)
function onTypeChange() {
  form.category = ''
  // 선택된 출금 계좌가 새 구분에서 허용되지 않으면 해제
  const fw = wallets.value.find((w) => w.id === form.walletId)
  if (fw && !fromWalletKinds.value.some((k) => k.value === fw.type)) form.walletId = ''
}

function todayStr() {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

async function loadCategories() {
  try {
    categories.value = await accountApi.categories()
  } catch {
    categories.value = []
  }
}

async function load() {
  loading.value = true
  try {
    const [ws, recs] = await Promise.all([
      accountApi.wallets(),
      isEdit ? accountApi.recurrings() : Promise.resolve([]),
    ])
    wallets.value = ws
    await loadCategories()
    if (isEdit) {
      const r = recs.find((x) => x.id === editId)
      if (!r) {
        formError.value = '정기결제를 찾을 수 없습니다.'
        return
      }
      Object.assign(form, {
        title: r.title,
        type: r.type,
        amount: r.amount,
        category: r.category || '',
        memo: r.memo || '',
        walletId: r.walletId || '',
        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,
      })
    } else {
      form.startDate = todayStr()
    }
  } catch (e) {
    formError.value = e.response?.data?.message || '불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}
onMounted(load)

function goBack() {
  if (window.history.length > 1) router.back()
  else router.replace('/account/recurrings')
}

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 (isEdit) await accountApi.updateRecurring(editId, payload)
    else await accountApi.createRecurring(payload)
    router.replace('/account/recurrings')
  } catch (e) {
    formError.value = e.response?.data?.message || '저장에 실패했습니다.'
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <section class="rform">
    <header class="rf-head">
      <span class="rf-title">정기결제 {{ isEdit ? '수정' : '추가' }}</span>
    </header>

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

    <form v-else 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>
        <AccountPicker
          v-model="form.walletId"
          :wallets="fromWallets"
          :disabled="submitting"
          title="계좌 선택" placeholder="계좌를 선택하세요"
          empty-text="등록된 계좌가 없습니다"
        />
      </div>

      <!-- 입금 계좌 (이체일 때만) -->
      <div v-if="form.type === 'TRANSFER'" class="field">
        <span class="field-label">입금 계좌</span>
        <AccountPicker
          v-model="form.toWalletId"
          :wallets="toWallets"
          :disabled="submitting"
          title="입금 계좌 선택" placeholder="계좌를 선택하세요"
          empty-text="등록된 계좌가 없습니다"
        />
      </div>

      <!-- 분류 — 트리거 → 바텀시트(CategoryPicker) (이체 제외) -->
      <div v-if="form.type !== 'TRANSFER'" 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="form.type"
          :categories="categories"
          :disabled="submitting"
          @category-added="loadCategories()"
        />
      </BottomSheet>

      <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 === '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="goBack" />
        <IconBtn icon="save" :title="isEdit ? '수정' : '등록'" variant="primary" type="submit" :disabled="submitting" />
      </div>
    </form>
  </section>
</template>

<style scoped>
.rform {
  max-width: 460px;
  margin: 0 auto;
}
.rf-head {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1.2rem;
}
.rf-title {
  font-size: 1.2rem;
  font-weight: 700;
}
.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 {
  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;
}
.chip.active {
  border-color: hsla(160, 100%, 37%, 1);
  background: hsla(160, 100%, 37%, 1);
  color: #fff;
}
.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;
}
/* 분류 시트 트리거(필드형) */
.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;
}
</style>
