<script setup lang="ts">
import type { EntryType } from "@cents/domain";
import {
  ArrowLeft,
  BookOpen,
  CalendarDays,
  Check,
  ChevronRight,
  CircleUserRound,
  Edit3,
  NotebookText,
  Trash2,
  WalletCards,
  X,
} from "@lucide/vue";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import {
  categories,
  entryTypes,
  findCategory,
  findCategoryPath,
  type Category,
} from "../data/categories";

const router = useRouter();
const editing = ref(false);
const categorySheetOpen = ref(false);
const savedToast = ref(false);
const draftParentId = ref("food");
const detailDateInput = ref<HTMLInputElement | null>(null);

const amount = ref("58.00");
const entryType = ref<EntryType>("expense");
const categoryId = ref("takeout");
const note = ref("午餐");
const occurredAt = ref("2026-07-19T12:28");
const ledger = ref("家庭日常");
const member = ref("小王");

const selectedCategory = computed(() => findCategory(categoryId.value));
const categoryPath = computed(() => findCategoryPath(entryType.value, categoryId.value));
const categoryLabel = computed(() => categoryPath.value.map((item) => item.label).join(" > "));
const draftParent = computed(() =>
  categories[entryType.value].find((category) => category.id === draftParentId.value),
);
const categoryChildren = computed(() => draftParent.value?.children ?? []);
const amountLabel = computed(() => {
  const value = Number(amount.value) || 0;
  return `${entryType.value === "expense" ? "−" : "+"} ¥${value.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
});
const dateLabel = computed(() => {
  const date = new Date(occurredAt.value);
  return new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(date);
});

function startEditing() {
  editing.value = true;
}

function cancelEditing() {
  editing.value = false;
  categorySheetOpen.value = false;
}

function savePrototype() {
  editing.value = false;
  categorySheetOpen.value = false;
  savedToast.value = true;
  window.setTimeout(() => (savedToast.value = false), 1600);
}

function setEntryType(type: EntryType) {
  if (entryType.value === type) return;
  entryType.value = type;
  const firstCategory = categories[type][0];
  draftParentId.value = firstCategory.id;
  categoryId.value = firstCategory.children?.[0]?.id ?? firstCategory.id;
}

function openCategorySheet() {
  draftParentId.value = categoryPath.value[0]?.id ?? categories[entryType.value][0].id;
  categorySheetOpen.value = true;
}

function openDetailDatePicker() {
  const input = detailDateInput.value;
  if (!input) return;
  if (typeof input.showPicker === "function") input.showPicker();
  else input.click();
}

function chooseParent(category: Category) {
  draftParentId.value = category.id;
  if (!category.children?.length) {
    categoryId.value = category.id;
    categorySheetOpen.value = false;
  }
}

function chooseChild(category: Category) {
  categoryId.value = category.id;
  categorySheetOpen.value = false;
}
</script>

<template>
  <main class="app-shell detail-prototype-shell">
    <header class="detail-appbar">
      <button class="detail-icon-button" type="button" aria-label="返回流水" title="返回" @click="router.push('/')">
        <ArrowLeft :size="22" />
      </button>
      <strong>条目明细</strong>
      <button
        v-if="!editing"
        class="detail-icon-button edit-entry-button"
        type="button"
        aria-label="编辑条目"
        title="编辑"
        @click="startEditing"
      >
        <Edit3 :size="20" />
      </button>
      <button
        v-else
        class="detail-icon-button"
        type="button"
        aria-label="取消编辑"
        title="取消"
        @click="cancelEditing"
      >
        <X :size="21" />
      </button>
    </header>

    <div class="detail-scroll">
      <section class="detail-amount-band" :class="entryType">
        <div
          class="detail-category-mark"
          :style="{
            color: selectedCategory?.color,
            background: selectedCategory?.tint,
          }"
        >
          <component :is="selectedCategory?.icon ?? WalletCards" :size="28" />
        </div>
        <span>{{ entryType === "expense" ? "支出" : "收入" }}</span>
        <strong v-if="!editing">{{ amountLabel }}</strong>
        <label v-else class="amount-edit-field">
          <span>¥</span>
          <input v-model="amount" inputmode="decimal" aria-label="金额" />
        </label>
      </section>

      <template v-if="!editing">
        <section class="detail-section" aria-label="条目信息">
          <div class="detail-row">
            <span class="detail-row-icon category"><WalletCards :size="19" /></span>
            <span class="detail-row-label">类别</span>
            <strong>{{ categoryLabel }}</strong>
          </div>
          <div class="detail-row">
            <span class="detail-row-icon date"><CalendarDays :size="19" /></span>
            <span class="detail-row-label">日期</span>
            <strong>{{ dateLabel }}</strong>
          </div>
          <div class="detail-row">
            <span class="detail-row-icon ledger"><BookOpen :size="19" /></span>
            <span class="detail-row-label">账本</span>
            <strong>{{ ledger }}</strong>
          </div>
          <div class="detail-row">
            <span class="detail-row-icon member"><CircleUserRound :size="19" /></span>
            <span class="detail-row-label">记录人</span>
            <strong>{{ member }}</strong>
          </div>
        </section>

        <section class="detail-section note-section" aria-label="备注">
          <div class="detail-row note-detail-row">
            <span class="detail-row-icon note"><NotebookText :size="19" /></span>
            <span class="detail-row-label">备注</span>
            <strong>{{ note || "无" }}</strong>
          </div>
        </section>

        <p class="entry-audit">由小王创建 · 2026年7月19日 12:29</p>
        <button class="delete-entry-command" type="button">
          <Trash2 :size="18" />
          删除条目
        </button>
      </template>

      <form v-else class="detail-edit-form" @submit.prevent="savePrototype">
        <fieldset class="type-segmented-control" aria-label="收支类型">
          <button
            v-for="type in entryTypes"
            :key="type.id"
            type="button"
            :class="{ active: entryType === type.id }"
            :style="{ '--type-color': type.color }"
            @click="setEntryType(type.id)"
          >
            <component :is="type.icon" :size="18" />
            {{ type.label }}
          </button>
        </fieldset>

        <section class="edit-fields" aria-label="编辑条目">
          <button class="edit-field-button" type="button" @click="openCategorySheet">
            <span class="edit-field-leading category"><WalletCards :size="19" /></span>
            <span class="edit-field-copy"><small>类别</small><strong>{{ categoryLabel }}</strong></span>
            <ChevronRight :size="19" />
          </button>

          <button class="edit-field-button" type="button" @click="openDetailDatePicker">
            <span class="edit-field-leading date"><CalendarDays :size="19" /></span>
            <span class="edit-field-copy">
              <small>日期时间</small>
              <strong>{{ dateLabel }}</strong>
            </span>
            <ChevronRight :size="19" />
          </button>
          <input
            ref="detailDateInput"
            v-model="occurredAt"
            class="detail-native-date-input"
            type="datetime-local"
            aria-label="日期时间"
            tabindex="-1"
          />

          <label class="edit-field-control">
            <span class="edit-field-leading ledger"><BookOpen :size="19" /></span>
            <span class="edit-field-copy">
              <small>账本</small>
              <select v-model="ledger" aria-label="账本">
                <option>家庭日常</option>
                <option>旅行账本</option>
              </select>
            </span>
          </label>

          <label class="edit-field-control">
            <span class="edit-field-leading member"><CircleUserRound :size="19" /></span>
            <span class="edit-field-copy">
              <small>记录人</small>
              <select v-model="member" aria-label="记录人">
                <option>小王</option>
                <option>自己</option>
              </select>
            </span>
          </label>

          <label class="edit-note-control">
            <span class="edit-field-leading note"><NotebookText :size="19" /></span>
            <span class="edit-field-copy">
              <small>备注</small>
              <textarea v-model="note" maxlength="120" rows="3" placeholder="补充说明"></textarea>
            </span>
          </label>
        </section>

        <div class="edit-actions">
          <button type="button" class="secondary-action" @click="cancelEditing">取消</button>
          <button type="submit" class="primary-action"><Check :size="19" />保存修改</button>
        </div>
      </form>
    </div>

    <Transition name="sheet">
      <div v-if="categorySheetOpen" class="category-sheet-layer">
        <button class="category-sheet-scrim" type="button" aria-label="关闭类别选择" @click="categorySheetOpen = false"></button>
        <section class="normal-category-sheet" aria-label="选择类别">
          <div class="category-sheet-handle"></div>
          <header>
            <strong>选择类别</strong>
            <button type="button" aria-label="关闭" title="关闭" @click="categorySheetOpen = false"><X :size="20" /></button>
          </header>

          <div class="sheet-type-tabs">
            <button
              v-for="type in entryTypes"
              :key="type.id"
              type="button"
              :class="{ active: entryType === type.id }"
              :style="{ '--type-color': type.color }"
              @click="setEntryType(type.id)"
            >
              <component :is="type.icon" :size="17" />{{ type.label }}
            </button>
          </div>

          <div class="category-grid" aria-label="一级类别">
            <button
              v-for="category in categories[entryType]"
              :key="category.id"
              type="button"
              :class="{ active: draftParentId === category.id }"
              :style="{ '--category-color': category.color, '--category-tint': category.tint }"
              @click="chooseParent(category)"
            >
              <span><component :is="category.icon" :size="22" /></span>
              <small>{{ category.label }}</small>
            </button>
          </div>

          <div v-if="categoryChildren.length" class="subcategory-area">
            <span>{{ draftParent?.label }}细分类</span>
            <div class="subcategory-list">
              <button
                v-for="category in categoryChildren"
                :key="category.id"
                type="button"
                :class="{ active: categoryId === category.id }"
                :style="{ '--category-color': category.color, '--category-tint': category.tint }"
                @click="chooseChild(category)"
              >
                <component :is="category.icon" :size="18" />
                {{ category.label }}
                <Check v-if="categoryId === category.id" :size="16" />
              </button>
            </div>
          </div>
        </section>
      </div>
    </Transition>

    <Transition name="toast">
      <div v-if="savedToast" class="detail-saved-toast" role="status"><Check :size="17" />修改已保存</div>
    </Transition>
  </main>
</template>

<style scoped>
.detail-prototype-shell {
  color: #1d2926;
  background: #f5f8f7;
}

.detail-appbar {
  position: relative;
  z-index: 2;
  height: calc(58px + env(safe-area-inset-top));
  display: grid;
  grid-template-columns: 44px 1fr 44px;
  align-items: end;
  gap: 8px;
  border-bottom: 1px solid #dce8e4;
  padding: env(safe-area-inset-top) 12px 7px;
  background: rgba(255, 255, 255, 0.96);
  backdrop-filter: blur(14px);
}

.detail-appbar > strong {
  align-self: center;
  text-align: center;
  font-size: 17px;
}

.detail-icon-button {
  width: 42px;
  height: 42px;
  display: grid;
  place-items: center;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: #31504a;
}

.edit-entry-button {
  background: #e8f7f3;
  color: #087f72;
}

.detail-scroll {
  height: calc(100% - 58px - env(safe-area-inset-top));
  overflow-y: auto;
  padding-bottom: calc(28px + env(safe-area-inset-bottom));
}

.detail-amount-band {
  min-height: 192px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #dce7e4;
  padding: 24px 18px;
  background: #ffffff;
}

.detail-category-mark {
  width: 54px;
  height: 54px;
  display: grid;
  place-items: center;
  border-radius: 14px;
}

.detail-amount-band > span {
  margin-top: 9px;
  color: #73817d;
  font-size: 13px;
}

.detail-amount-band > strong {
  margin-top: 3px;
  color: #d84c36;
  font-size: 34px;
  font-variant-numeric: tabular-nums;
  line-height: 1.25;
}

.detail-amount-band.income > strong {
  color: #0d8b67;
}

.detail-section {
  margin-top: 12px;
  border-top: 1px solid #dce7e4;
  border-bottom: 1px solid #dce7e4;
  padding: 0 16px;
  background: #ffffff;
}

.detail-row {
  min-height: 62px;
  display: grid;
  grid-template-columns: 34px 64px minmax(0, 1fr);
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #e5edeb;
}

.detail-row:last-child {
  border-bottom: 0;
}

.detail-row-icon,
.edit-field-leading {
  width: 32px;
  height: 32px;
  display: grid;
  place-items: center;
  border-radius: 8px;
}

.detail-row-icon.category,
.edit-field-leading.category { background: #fff0e8; color: #e85e2b; }
.detail-row-icon.date,
.edit-field-leading.date { background: #fff7dd; color: #9b6d0f; }
.detail-row-icon.ledger,
.edit-field-leading.ledger { background: #e9f7f3; color: #087f72; }
.detail-row-icon.member,
.edit-field-leading.member { background: #edf4ff; color: #3478e5; }
.detail-row-icon.note,
.edit-field-leading.note { background: #f3efff; color: #7559d9; }

.detail-row-label {
  color: #7b8884;
  font-size: 13px;
}

.detail-row strong {
  min-width: 0;
  overflow-wrap: anywhere;
  text-align: right;
  font-size: 14px;
  font-weight: 650;
}

.note-section {
  margin-top: 12px;
}

.note-detail-row {
  align-items: start;
  min-height: 84px;
  padding: 14px 0;
}

.note-detail-row .detail-row-label,
.note-detail-row strong {
  padding-top: 6px;
}

.entry-audit {
  margin: 18px 16px 10px;
  color: #8b9693;
  text-align: center;
  font-size: 12px;
}

.delete-entry-command {
  min-height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  margin: 0 auto;
  border: 0;
  padding: 0 12px;
  background: transparent;
  color: #c94635;
  font-size: 14px;
}

.amount-edit-field {
  width: min(100%, 270px);
  height: 54px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  margin-top: 5px;
  border-bottom: 2px solid #ef6a4d;
  color: #d84c36;
}

.income .amount-edit-field {
  border-bottom-color: #16966f;
  color: #0d8b67;
}

.amount-edit-field > span {
  font-size: 23px;
  font-weight: 700;
}

.amount-edit-field input {
  width: 200px;
  border: 0;
  padding: 0;
  outline: 0;
  background: transparent;
  color: inherit;
  font-size: 36px;
  font-weight: 760;
  font-variant-numeric: tabular-nums;
  text-align: center;
}

.detail-edit-form {
  padding-bottom: 86px;
}

.type-segmented-control {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px;
  margin: 12px 16px;
  border: 0;
  border-radius: 8px;
  padding: 4px;
  background: #e9efed;
}

.type-segmented-control button {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  border: 0;
  border-radius: 6px;
  background: transparent;
  color: #70807c;
  font-size: 14px;
  font-weight: 680;
}

.type-segmented-control button.active {
  background: #ffffff;
  color: var(--type-color);
  box-shadow: 0 2px 8px rgba(28, 52, 47, 0.12);
}

.edit-fields {
  border-top: 1px solid #dce7e4;
  border-bottom: 1px solid #dce7e4;
  padding: 0 16px;
  background: #ffffff;
}

.edit-field-button,
.edit-field-control,
.edit-note-control {
  width: 100%;
  min-height: 66px;
  display: grid;
  grid-template-columns: 34px minmax(0, 1fr) auto;
  align-items: center;
  gap: 10px;
  border: 0;
  border-bottom: 1px solid #e3ece9;
  padding: 8px 0;
  background: transparent;
  color: #27342f;
  text-align: left;
}

.edit-field-control:last-of-type {
  border-bottom: 1px solid #e3ece9;
}

.edit-field-copy {
  min-width: 0;
  display: grid;
  gap: 2px;
}

.edit-field-copy small {
  color: #7b8884;
  font-size: 11px;
}

.edit-field-copy strong {
  font-size: 14px;
}

.edit-field-copy input,
.edit-field-copy select,
.edit-field-copy textarea {
  width: 100%;
  border: 0;
  border-radius: 0;
  padding: 0;
  outline: 0;
  background: transparent;
  color: #27342f;
  font-size: 14px;
}

.detail-native-date-input {
  position: absolute;
  width: 1px;
  height: 1px;
  opacity: 0;
  pointer-events: none;
}

.edit-field-copy textarea {
  min-height: 66px;
  resize: none;
  line-height: 1.45;
}

.edit-note-control {
  align-items: start;
  border-bottom: 0;
  padding-top: 12px;
}

.edit-note-control .edit-field-leading {
  margin-top: 3px;
}

.edit-actions {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 3;
  display: grid;
  grid-template-columns: 1fr 1.35fr;
  gap: 10px;
  border-top: 1px solid #d8e5e1;
  padding: 10px 16px calc(10px + env(safe-area-inset-bottom));
  background: rgba(255, 255, 255, 0.97);
  backdrop-filter: blur(14px);
}

.edit-actions button {
  height: 46px;
  border-radius: 8px;
  font-weight: 720;
}

.secondary-action {
  border: 1px solid #cbdad6;
  background: #ffffff;
  color: #48605a;
}

.primary-action {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  border: 0;
  background: #087f72;
  color: #ffffff;
}

.category-sheet-layer {
  position: absolute;
  inset: 0;
  z-index: 10;
}

.category-sheet-scrim {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  border: 0;
  background: rgba(18, 35, 32, 0.42);
  backdrop-filter: blur(3px);
}

.normal-category-sheet {
  position: absolute;
  top: 22%;
  right: 0;
  bottom: 0;
  left: 0;
  overflow-y: auto;
  border-radius: 14px 14px 0 0;
  padding: 0 16px calc(20px + env(safe-area-inset-bottom));
  background: #ffffff;
  box-shadow: 0 -16px 36px rgba(22, 45, 40, 0.22);
}

.category-sheet-handle {
  width: 38px;
  height: 4px;
  margin: 8px auto 3px;
  border-radius: 2px;
  background: #b9cac5;
}

.normal-category-sheet header {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.normal-category-sheet header > strong {
  font-size: 16px;
}

.normal-category-sheet header button {
  width: 38px;
  height: 38px;
  display: grid;
  place-items: center;
  border: 0;
  border-radius: 8px;
  background: #f0f5f3;
  color: #536762;
}

.sheet-type-tabs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  margin-bottom: 16px;
}

.sheet-type-tabs button {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  border: 1px solid #d8e4e1;
  border-radius: 8px;
  background: #ffffff;
  color: #60716d;
  font-weight: 680;
}

.sheet-type-tabs button.active {
  border-color: var(--type-color);
  background: color-mix(in srgb, var(--type-color) 10%, white);
  color: var(--type-color);
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px 8px;
}

.category-grid button {
  min-width: 0;
  display: grid;
  place-items: center;
  gap: 5px;
  border: 0;
  padding: 0;
  background: transparent;
  color: #53615e;
}

.category-grid button > span {
  width: 48px;
  height: 48px;
  display: grid;
  place-items: center;
  border: 2px solid transparent;
  border-radius: 50%;
  background: var(--category-tint);
  color: var(--category-color);
}

.category-grid button.active > span {
  border-color: var(--category-color);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--category-color) 13%, white);
}

.category-grid small {
  overflow: hidden;
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.subcategory-area {
  margin-top: 18px;
  border-top: 1px solid #e1ebe8;
  padding-top: 14px;
}

.subcategory-area > span {
  color: #75827f;
  font-size: 12px;
  font-weight: 650;
}

.subcategory-list {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 8px;
  margin-top: 9px;
}

.subcategory-list button {
  min-width: 0;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  overflow: hidden;
  border: 1px solid color-mix(in srgb, var(--category-color) 24%, #d8e4e1);
  border-radius: 8px;
  padding: 0 8px;
  background: var(--category-tint);
  color: var(--category-color);
  font-size: 12px;
  font-weight: 650;
  white-space: nowrap;
}

.subcategory-list button.active {
  border-color: var(--category-color);
}

.detail-saved-toast {
  position: absolute;
  right: 50%;
  bottom: 28px;
  z-index: 20;
  min-height: 40px;
  display: flex;
  align-items: center;
  gap: 7px;
  transform: translateX(50%);
  border-radius: 8px;
  padding: 0 14px;
  background: #173c35;
  color: #ffffff;
  box-shadow: 0 10px 24px rgba(21, 50, 44, 0.2);
  font-size: 13px;
  white-space: nowrap;
}

.sheet-enter-active,
.sheet-leave-active {
  transition: opacity 180ms ease;
}

.sheet-enter-active .normal-category-sheet,
.sheet-leave-active .normal-category-sheet {
  transition: transform 220ms ease;
}

.sheet-enter-from,
.sheet-leave-to {
  opacity: 0;
}

.sheet-enter-from .normal-category-sheet,
.sheet-leave-to .normal-category-sheet {
  transform: translateY(100%);
}

@media (max-width: 360px) {
  .detail-row {
    grid-template-columns: 34px 54px minmax(0, 1fr);
  }

  .category-grid {
    column-gap: 4px;
  }
}
</style>
