<script setup>
import { onBeforeUnmount, onMounted, ref, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import Sortable from 'sortablejs'
import { accountApi } from '@/api/accountApi'
import IconBtn from '@/components/ui/IconBtn.vue'

const router = useRouter()

const categories = ref([])
const rows = ref([]) // 현재 탭(activeType)의 분류 — 드래그 정렬 대상
const loading = ref(false)
const error = ref(null)
const activeType = ref('EXPENSE') // EXPENSE / INCOME
const newName = ref('')

// categories/activeType 변경 시 현재 탭 목록 동기화 (백엔드가 sort_order 순 정렬)
function syncRows() {
  rows.value = categories.value.filter((c) => c.type === activeType.value)
}
watch([categories, activeType], syncRows, { immediate: true })

async function load() {
  loading.value = true
  error.value = null
  try {
    categories.value = await accountApi.categories()
  } catch (e) {
    error.value = e.response?.data?.message || '불러오지 못했습니다.'
  } finally {
    loading.value = false
  }
}

// ===== 드래그앤드랍 정렬 (SortableJS, 터치 지원) =====
const listEl = ref(null)
let sortable = null
function initSortable() {
  if (sortable) {
    sortable.destroy()
    sortable = null
  }
  if (!listEl.value) return
  sortable = Sortable.create(listEl.value, {
    handle: '.drag-handle',
    animation: 150,
    onEnd: (evt) => {
      if (evt.oldIndex === evt.newIndex) return
      const arr = rows.value
      const moved = arr.splice(evt.oldIndex, 1)[0]
      arr.splice(evt.newIndex, 0, moved)
      persistOrder(arr.map((r) => r.id))
    },
  })
}
async function persistOrder(ids) {
  try {
    await accountApi.reorderCategories(activeType.value, ids)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '순서 저장에 실패했습니다.')
    await load()
  }
}

async function addCategory() {
  const name = newName.value.trim()
  if (!name) return
  try {
    await accountApi.createCategory({ type: activeType.value, name })
    newName.value = ''
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '추가에 실패했습니다.')
  }
}

async function saveCategory(c) {
  const name = (c.name || '').trim()
  if (!name) return
  try {
    await accountApi.updateCategory(c.id, { type: c.type, name })
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '수정에 실패했습니다.')
  }
}

async function removeCategory(c) {
  if (!confirm(`'${c.name}' 분류를 삭제할까요? (기존 내역의 분류명은 그대로 유지됩니다)`)) return
  try {
    await accountApi.removeCategory(c.id)
    await load()
  } catch (e) {
    alert(e.response?.data?.message || '삭제에 실패했습니다.')
  }
}

async function importExisting() {
  if (!confirm('기존 내역에서 사용한 분류들을 목록으로 가져올까요?')) return
  try {
    categories.value = await accountApi.importCategories()
  } catch (e) {
    alert(e.response?.data?.message || '불러오기에 실패했습니다.')
  }
}

onMounted(async () => {
  await load()
  await nextTick()
  initSortable()
})
onBeforeUnmount(() => sortable?.destroy())
</script>

<template>
  <section class="cat">
    <header class="head">
      <h1>분류 관리</h1>
      <div class="head-actions">
        <button type="button" class="text-btn" @click="importExisting">기존 분류 불러오기</button>
        <IconBtn icon="back" title="가계부로" @click="router.push('/account')" />
      </div>
    </header>
    <p class="hint">내역·예산에서 선택할 분류를 관리합니다. 분류 이름을 바꾸면 기존 내역·예산에도 반영됩니다.</p>

    <div class="tabs">
      <button type="button" :class="{ active: activeType === 'EXPENSE' }" @click="activeType = 'EXPENSE'">지출 분류</button>
      <button type="button" :class="{ active: activeType === 'INCOME' }" @click="activeType = 'INCOME'">수입 분류</button>
    </div>

    <form class="new-cat" @submit.prevent="addCategory">
      <input v-model="newName" type="text" :placeholder="activeType === 'EXPENSE' ? '예: 식비, 교통' : '예: 급여, 용돈'" />
      <IconBtn icon="plus" title="추가" variant="primary" type="submit" />
    </form>
    <p class="hint sm">≡ 손잡이를 끌어 순서를 바꾸면 내역 추가 화면에도 그 순서로 나옵니다.</p>

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

    <ul v-show="!loading && rows.length" ref="listEl" class="cat-list">
      <li v-for="c in rows" :key="c.id" :data-id="c.id" class="cat-row">
        <span class="drag-handle" title="드래그하여 순서 변경">≡</span>
        <input v-model="c.name" class="cat-name" @keyup.enter="saveCategory(c)" />
        <IconBtn icon="check" title="저장" @click="saveCategory(c)" />
        <IconBtn icon="trash" title="삭제" variant="danger" @click="removeCategory(c)" />
      </li>
    </ul>
    <p v-if="!loading && !rows.length" class="msg">
      등록된 {{ activeType === 'EXPENSE' ? '지출' : '수입' }} 분류가 없습니다.
    </p>
  </section>
</template>

<style scoped>
.cat {
  max-width: 560px;
  margin: 0 auto;
}
.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.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;
}
input {
  padding: 0.5rem 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
}
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.danger {
  border-color: #c0392b;
  color: #c0392b;
}
.tabs {
  display: flex;
  gap: 0.25rem;
  border-bottom: 1px solid var(--color-border);
  margin-bottom: 1rem;
}
.tabs button {
  border: 0;
  border-bottom: 2px solid transparent;
  border-radius: 0;
  background: transparent;
  padding: 0.6rem 1rem;
}
.tabs button.active {
  border-bottom-color: hsla(160, 100%, 37%, 1);
  color: hsla(160, 100%, 37%, 1);
  font-weight: 600;
}
.new-cat {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}
.new-cat input {
  flex: 1;
}
.cat-list {
  list-style: none;
  padding-left: 0;
  margin: 0;
}
.cat-row {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  padding: 0.4rem 0;
  border-bottom: 1px solid var(--color-border);
  background: var(--color-background);
}
.drag-handle {
  cursor: grab;
  user-select: none;
  opacity: 0.5;
  font-size: 1.1rem;
  padding: 0 0.2rem;
  touch-action: none;
}
.drag-handle:active {
  cursor: grabbing;
}
.cat-name {
  flex: 1;
}
.hint.sm {
  font-size: 0.78rem;
  margin: 0 0 0.75rem;
}
.msg {
  margin: 0.75rem 0;
}
.msg.error {
  color: #c0392b;
}
</style>
