<script setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import Sortable from 'sortablejs'
import { accountApi } from '@/api/accountApi'

const props = defineProps({
  modelValue:  { type: String,  default: '' },
  type:        { type: String,  required: true },
  categories:  { type: Array,   default: () => [] },
  disabled:    { type: Boolean, default: false },
  admin:       { type: Boolean, default: false },
  reorderable: { type: Boolean, default: false },
  hideAdd:     { type: Boolean, default: false }, // 분류 추가(+대분류/+소분류) 버튼 숨김 (필터 등 선택 전용)
})
const emit = defineEmits(['update:modelValue', 'category-added', 'rename', 'delete', 'reorder'])

// ─── accordion state ───────────────────────────────────────────────────
const categoryMajor = ref('')

const majorOptions = computed(() =>
  props.categories.filter((c) => c.type === props.type && c.parentId == null)
)
// select 모드: 4개씩 행 분할
const majorRows = computed(() => {
  const rows = []
  for (let i = 0; i < majorOptions.value.length; i += 4)
    rows.push(majorOptions.value.slice(i, i + 4))
  return rows
})
// admin 일반 모드: 2개씩 행 분할 (이름+아이콘 공간 확보)
const adminRows = computed(() => {
  const rows = []
  for (let i = 0; i < majorOptions.value.length; i += 2)
    rows.push(majorOptions.value.slice(i, i + 2))
  return rows
})
const selectedMajorObj = computed(() =>
  majorOptions.value.find((m) => m.name === categoryMajor.value) ?? null
)
function subsByMajor(majorId) {
  return props.categories.filter((c) => c.parentId === majorId)
}

// select 모드: 클릭 시 accordion 토글 + 값 emit
function onMajorClick(major) {
  if (categoryMajor.value === major.name) {
    categoryMajor.value = ''
    emit('update:modelValue', '')
  } else {
    categoryMajor.value = major.name
    if (!subsByMajor(major.id).length) emit('update:modelValue', major.name)
    else emit('update:modelValue', '')
  }
}
// admin 모드: 클릭 시 accordion 토글만 (값 emit 없음)
function onAdminMajorClick(major) {
  categoryMajor.value = categoryMajor.value === major.name ? '' : major.name
}

// modelValue / type / categories 변경 시 대분류 상태 동기화
function syncFromValue() {
  if (props.admin) return
  const cur = props.modelValue
  if (!cur) { categoryMajor.value = ''; return }
  const c = props.categories.find((x) => x.type === props.type && x.name === cur)
  if (c && c.parentId != null) {
    const parent = props.categories.find((x) => x.id === c.parentId)
    categoryMajor.value = parent ? parent.name : cur
  } else {
    categoryMajor.value = cur
  }
}
watch(() => [props.modelValue, props.type, props.categories], syncFromValue, { immediate: true })

// ─── 인라인 분류 추가 ──────────────────────────────────────────────────
const addingCategory = ref(false)
const addingAsMajor  = ref(true)
const newCategoryName = ref('')
const catSubmitting  = ref(false)

function startAddMajor() {
  if (!props.admin) { categoryMajor.value = ''; emit('update:modelValue', '') }
  newCategoryName.value = ''
  addingAsMajor.value = true
  addingCategory.value = true
}
function startAddSub() {
  newCategoryName.value = ''
  addingAsMajor.value = false
  addingCategory.value = true
}
function cancelAdd() {
  addingCategory.value = false
  newCategoryName.value = ''
}
async function confirmAdd() {
  const name = newCategoryName.value.trim()
  if (!name) return
  catSubmitting.value = true
  const parent = props.categories.find(
    (c) => c.type === props.type && c.parentId == null && c.name === categoryMajor.value,
  )
  const parentId = parent ? parent.id : null
  try {
    await accountApi.createCategory({ type: props.type, name, parentId })
    emit('category-added')
    if (!props.admin) {
      emit('update:modelValue', name)
      if (!parentId) categoryMajor.value = name
    } else {
      if (!parentId) categoryMajor.value = name
    }
    cancelAdd()
  } catch (e) {
    if (e.response?.status === 409) {
      if (!props.admin) emit('update:modelValue', name)
      syncFromValue()
      cancelAdd()
    } else {
      alert(e.response?.data?.message || '분류 추가에 실패했습니다.')
    }
  } finally {
    catSubmitting.value = false
  }
}

// ─── Admin: 인라인 이름 수정 ───────────────────────────────────────────
const editingId = ref(null)
const editingName = ref('')
const editingCategory = ref(null)

function startEdit(c) {
  editingId.value = c.id
  editingName.value = c.name
  editingCategory.value = c
  nextTick(() => {
    const input = document.querySelector('.adm-edit-input')
    if (input) input.focus()
  })
}
function cancelEdit() {
  editingId.value = null
  editingName.value = ''
  editingCategory.value = null
}
function confirmEdit() {
  const name = editingName.value.trim()
  if (name && editingCategory.value && name !== editingCategory.value.name) {
    emit('rename', editingCategory.value, name)
  }
  cancelEdit()
}

// ─── Admin: SortableJS (순서변경 모드에서만 활성) ─────────────────────
const majorGridEl = ref(null)
const subGridEl   = ref(null)
let majorSortable = null
let subSortable   = null

function destroySortables() {
  majorSortable?.destroy(); majorSortable = null
  subSortable?.destroy();   subSortable   = null
}
function initMajorSortable() {
  if (!props.admin || !props.reorderable || !majorGridEl.value) return
  majorSortable?.destroy()
  majorSortable = Sortable.create(majorGridEl.value, {
    handle: '.adm-handle',
    draggable: '.admin-chip',
    animation: 150,
    onEnd: () => {
      const ids = [...majorGridEl.value.querySelectorAll(':scope > .admin-chip')]
        .map((el) => Number(el.dataset.id))
      emit('reorder', ids)
    },
  })
}
function initSubSortable() {
  if (!props.admin || !props.reorderable || !subGridEl.value) return
  subSortable?.destroy()
  subSortable = Sortable.create(subGridEl.value, {
    handle: '.adm-handle',
    draggable: '.admin-chip',
    animation: 150,
    onEnd: () => {
      const ids = [...subGridEl.value.querySelectorAll(':scope > .admin-chip')]
        .map((el) => Number(el.dataset.id))
      if (ids.length) emit('reorder', ids)
    },
  })
}

watch(majorGridEl, (el) => { if (el && props.admin && props.reorderable) initMajorSortable() })
watch(subGridEl,   (el) => { if (el && props.admin && props.reorderable) initSubSortable() })
watch(
  () => [props.admin, props.reorderable, props.categories],
  async () => {
    if (!props.admin || !props.reorderable) { destroySortables(); return }
    await nextTick()
    initMajorSortable()
    initSubSortable()
  },
)

onBeforeUnmount(destroySortables)
</script>

<template>
  <!-- ═══ SELECT MODE ══════════════════════════════════════════ -->
  <template v-if="!admin">
    <div v-if="!addingCategory" class="cat-picker">
      <template v-for="(row, rowIdx) in majorRows" :key="rowIdx">
        <div class="acc-major-grid">
          <button
            v-for="m in row" :key="m.id"
            type="button" class="acc-chip major"
            :class="{ active: categoryMajor === m.name }"
            :disabled="disabled"
            @click="onMajorClick(m)"
          >{{ m.name }}</button>
        </div>
        <div
          v-if="selectedMajorObj && row.some(m => m.id === selectedMajorObj.id)"
          class="acc-sub-grid"
        >
          <button
            v-for="s in subsByMajor(selectedMajorObj.id)" :key="s.id"
            type="button" class="acc-chip sub"
            :class="{ active: modelValue === s.name }"
            :disabled="disabled"
            @click="$emit('update:modelValue', s.name)"
          >{{ s.name }}</button>
          <button v-if="!hideAdd" type="button" class="acc-chip add-chip sub-add" :disabled="disabled" @click="startAddSub">+ 소분류</button>
        </div>
      </template>
      <button v-if="!hideAdd" type="button" class="acc-chip add-chip" :disabled="disabled" @click="startAddMajor">+ 대분류</button>
    </div>
    <div v-else class="cat-input">
      <input
        v-model="newCategoryName" type="text"
        :placeholder="addingAsMajor
          ? (type === 'EXPENSE' ? '새 지출 대분류' : '새 수입 대분류')
          : `${categoryMajor} > 새 소분류`"
        :disabled="catSubmitting"
        @keyup.enter.prevent="confirmAdd"
      />
      <button type="button" class="cat-add-btn primary" :disabled="catSubmitting" @click="confirmAdd">확인</button>
      <button type="button" class="cat-add-btn" :disabled="catSubmitting" @click="cancelAdd">취소</button>
    </div>
  </template>

  <!-- ═══ ADMIN MODE ════════════════════════════════════════════ -->
  <template v-else>
    <div v-if="!addingCategory" class="cat-picker">

      <!-- ─── 일반 모드: 행 단위, 소분류 정위치 ─────────────── -->
      <template v-if="!reorderable">
        <template v-for="(row, rowIdx) in adminRows" :key="rowIdx">
          <div class="acc-major-grid">
            <div
              v-for="m in row" :key="m.id"
              class="acc-chip major admin-chip"
              :class="{ active: categoryMajor === m.name }"
              @click="onAdminMajorClick(m)"
            >
              <template v-if="editingId === m.id">
                <input
                  v-model="editingName" class="adm-edit-input"
                  @keyup.enter.stop="confirmEdit" @keyup.escape="cancelEdit" @click.stop
                />
                <button type="button" class="adm-ok" @mousedown.prevent @click.stop="confirmEdit">✓</button>
              </template>
              <span v-else class="adm-label">{{ m.name }}</span>
              <button v-if="editingId !== m.id" type="button" class="adm-edit-btn" title="이름 수정" @click.stop="startEdit(m)">✏</button>
              <button type="button" class="adm-del" title="삭제" @click.stop="$emit('delete', m)">✕</button>
            </div>
          </div>
          <!-- 이 행에 선택된 대분류가 있을 때만 바로 아래에 소분류 트레이 노출 -->
          <div
            v-if="selectedMajorObj && row.some(m => m.id === selectedMajorObj.id)"
            class="acc-sub-grid adm-sub-grid"
          >
            <div
              v-for="s in subsByMajor(selectedMajorObj.id)" :key="s.id"
              class="acc-chip sub admin-chip"
              :data-id="s.id"
            >
              <template v-if="editingId === s.id">
                <input
                  v-model="editingName" class="adm-edit-input"
                  @keyup.enter.stop="confirmEdit" @keyup.escape="cancelEdit" @click.stop
                />
                <button type="button" class="adm-ok" @mousedown.prevent @click.stop="confirmEdit">✓</button>
              </template>
              <span v-else class="adm-label">{{ s.name }}</span>
              <button v-if="editingId !== s.id" type="button" class="adm-edit-btn" title="이름 수정" @click.stop="startEdit(s)">✏</button>
              <button type="button" class="adm-del" title="삭제" @click.stop="$emit('delete', s)">✕</button>
            </div>
            <button type="button" class="acc-chip add-chip sub-add" @click="startAddSub">+ 소분류</button>
          </div>
        </template>
        <button type="button" class="acc-chip add-chip" @click="startAddMajor">+ 대분류</button>
      </template>

      <!-- ─── 순서변경 모드: flat 그리드 + SortableJS ──────── -->
      <template v-else>
        <div class="acc-major-grid adm-grid" ref="majorGridEl">
          <div
            v-for="m in majorOptions" :key="m.id"
            class="acc-chip major admin-chip"
            :class="{ active: categoryMajor === m.name }"
            :data-id="m.id"
            @click="onAdminMajorClick(m)"
          >
            <span class="adm-handle" @click.stop>⠿</span>
            <span class="adm-label">{{ m.name }}</span>
          </div>
        </div>
        <!-- 선택된 대분류의 소분류 순서 변경 -->
        <div
          v-if="selectedMajorObj"
          class="acc-sub-grid adm-sub-grid"
          ref="subGridEl"
          :data-major="selectedMajorObj.id"
        >
          <div
            v-for="s in subsByMajor(selectedMajorObj.id)" :key="s.id"
            class="acc-chip sub admin-chip"
            :data-id="s.id"
          >
            <span class="adm-handle" @click.stop>⠿</span>
            <span class="adm-label">{{ s.name }}</span>
          </div>
        </div>
      </template>

    </div>
    <div v-else class="cat-input">
      <input
        v-model="newCategoryName" type="text"
        :placeholder="addingAsMajor
          ? (type === 'EXPENSE' ? '새 지출 대분류' : '새 수입 대분류')
          : `${categoryMajor} > 새 소분류`"
        :disabled="catSubmitting"
        @keyup.enter.prevent="confirmAdd"
      />
      <button type="button" class="cat-add-btn primary" :disabled="catSubmitting" @click="confirmAdd">확인</button>
      <button type="button" class="cat-add-btn" :disabled="catSubmitting" @click="cancelAdd">취소</button>
    </div>
  </template>
</template>

<style scoped>
.cat-picker {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}
.acc-major-grid,
.acc-sub-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
}
.acc-sub-grid {
  padding: 0.45rem;
  border-radius: 0 6px 6px 6px;
  background: var(--color-background-mute);
  border-left: 3px solid hsla(160, 100%, 37%, 0.4);
}
.acc-chip {
  flex: 1 1 calc(25% - 0.35rem);
  min-width: 0;
  padding: 0.38rem 0.4rem;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  font-size: 0.82rem;
  color: var(--color-text);
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.acc-chip:disabled { opacity: 0.45; cursor: not-allowed; }
.acc-chip.major.active {
  border-color: hsla(160, 100%, 37%, 1);
  background: hsla(160, 100%, 37%, 0.1);
  color: hsla(160, 100%, 37%, 1);
  font-weight: 600;
}
.acc-chip.sub { background: transparent; }
.acc-chip.sub.active {
  border-color: hsla(160, 100%, 37%, 1);
  background: hsla(160, 100%, 37%, 0.1);
  color: hsla(160, 100%, 37%, 1);
  font-weight: 600;
}
.acc-chip.add-chip {
  opacity: 0.55;
  border-style: dashed;
}
.acc-chip.add-chip.sub-add { flex: 0 0 auto; }

/* ── admin 칩 공통 ──────────────────────────────────────── */
/* 2개씩 한 줄 (이름+아이콘 공간 확보) */
.admin-chip {
  flex: 1 1 calc(50% - 0.35rem) !important;
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.32rem 0.4rem;
  text-align: left;
  cursor: default;
  overflow: visible;
}
.adm-handle {
  flex-shrink: 0;
  cursor: grab;
  color: var(--color-text);
  opacity: 0.35;
  font-size: 0.85rem;
  touch-action: none;
  user-select: none;
  line-height: 1;
}
.adm-handle:active { cursor: grabbing; }
.adm-label {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
}
.adm-edit-input {
  flex: 1;
  min-width: 0;
  padding: 0.1rem 0.3rem;
  border: 1px solid var(--color-border);
  border-radius: 3px;
  background: var(--color-background);
  color: var(--color-text);
  font-size: 0.8rem;
}
.adm-ok {
  flex-shrink: 0;
  width: 1.3rem;
  height: 1.3rem;
  border: 1px solid hsla(160, 100%, 37%, 0.5);
  border-radius: 3px;
  background: hsla(160, 100%, 37%, 0.1);
  color: hsla(160, 100%, 37%, 1);
  font-size: 0.65rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.adm-edit-btn {
  flex-shrink: 0;
  width: 1.3rem;
  height: 1.3rem;
  border: 1px solid var(--color-border);
  border-radius: 3px;
  background: transparent;
  color: var(--color-text);
  opacity: 0.45;
  font-size: 0.65rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.adm-edit-btn:hover { opacity: 0.9; }
.adm-del {
  flex-shrink: 0;
  width: 1.3rem;
  height: 1.3rem;
  border: 1px solid rgba(192, 57, 43, 0.3);
  border-radius: 3px;
  background: rgba(192, 57, 43, 0.06);
  color: #c0392b;
  font-size: 0.65rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.adm-del:hover { background: rgba(192, 57, 43, 0.15); }

.adm-sub-grid {
  gap: 0.3rem;
  background: var(--color-background-mute);
  border-left: 3px solid hsla(160, 100%, 37%, 0.4);
  border-radius: 0 6px 6px 6px;
  padding: 0.45rem;
}
/* 소분류 칩은 트레이 배경이 보이도록 투명 처리 */
.adm-sub-grid .admin-chip {
  background: transparent;
}

/* ── 인라인 추가 입력 ──────────────────────────────────── */
.cat-input {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
  align-items: center;
}
.cat-input input {
  flex: 1;
  min-width: 0;
  padding: 0.45rem 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-size: 0.85rem;
}
.cat-add-btn {
  padding: 0.38rem 0.7rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background: var(--color-background-soft);
  color: var(--color-text);
  font-size: 0.82rem;
  cursor: pointer;
  white-space: nowrap;
}
.cat-add-btn.primary {
  border-color: hsla(160, 100%, 37%, 1);
  color: hsla(160, 100%, 37%, 1);
}
.cat-add-btn:disabled { opacity: 0.5; cursor: not-allowed; }
</style>
