<script setup lang="ts">
import type { CurrencyCode, LedgerAmountDisplayMode, LedgerIconKey, LedgerThemeId } from "@cents/domain";
import { ArrowLeft, Check } from "@lucide/vue";
import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import LedgerIconPicker from "../components/LedgerIconPicker.vue";
import { ledgerTheme, ledgerThemes, type LedgerSummaryRange } from "../data/ledgers";
import { useLedgerStore } from "../stores/ledgers";

const router = useRouter();
const ledgerStore = useLedgerStore();
const name = ref("");
const themeId = ref<LedgerThemeId>("jade");
const currency = ref<CurrencyCode>("CNY");
const amountDisplay = ref<LedgerAmountDisplayMode>("base");
const iconKey = ref<LedgerIconKey>("wallet");
const summaryRange = ref<LedgerSummaryRange>("year");
const saving = ref(false);

onMounted(async () => {
  await ledgerStore.loadLedgers();
  if (ledgerStore.currentRole !== "owner") {
    await router.replace("/");
    return;
  }
  if (!ledgerStore.currentLedger) return;
  name.value = ledgerStore.currentLedger.name;
  themeId.value = ledgerStore.currentLedger.theme;
  currency.value = ledgerStore.currentLedger.defaultCurrency;
  amountDisplay.value = ledgerStore.currentLedger.amountDisplay;
  iconKey.value = ledgerStore.currentLedger.icon;
  summaryRange.value = ledgerStore.currentLedger.summaryRange;
});

watch(summaryRange, (value) => {
  if (ledgerStore.currentLedgerId) void ledgerStore.setSummaryRange(ledgerStore.currentLedgerId, value);
});

async function save() {
  if (!ledgerStore.currentLedger || !name.value.trim()) return;
  saving.value = true;
  const theme = ledgerTheme(themeId.value);
  await ledgerStore.updateLedger({ id: ledgerStore.currentLedger.id, name: name.value, color: theme.accent, theme: theme.id, icon: iconKey.value, defaultCurrency: currency.value, amountDisplay: amountDisplay.value });
  saving.value = false;
  await router.back();
}
</script>

<template>
  <main class="app-shell ledger-settings-shell">
    <header class="settings-appbar">
      <button type="button" aria-label="返回" title="返回" @click="router.back()"><ArrowLeft :size="22" /></button>
      <strong>账本设置</strong><span></span>
    </header>
    <form class="settings-form" @submit.prevent="save">
      <section>
        <label><span>账本名称</span><input v-model="name" maxlength="24" :disabled="ledgerStore.currentLedger?.isPersonal" required /></label>
        <label><span>默认币种 · 暂不可修改</span><select v-model="currency" disabled title="默认币种暂不可修改"><option value="CNY">人民币 CNY</option><option value="USD">美元 USD</option><option value="EUR">欧元 EUR</option><option value="JPY">日元 JPY</option><option value="THB">泰铢 THB</option><option value="HKD">港币 HKD</option></select></label>
        <label><span>流水金额显示</span><select v-model="amountDisplay"><option value="base">本币金额（人民币）</option><option value="original">原币金额</option></select></label>
        <label><span>流水页头统计范围</span><select v-model="summaryRange"><option value="year">当年累计</option><option value="ledger">账本累计</option></select></label>
      </section>
      <section class="color-setting">
        <span>账本主题</span>
        <div>
          <button v-for="theme in ledgerThemes" :key="theme.id" type="button" :class="{ active: themeId === theme.id }" :style="{ background: theme.gradient }" :aria-label="`选择${theme.name}主题`" :title="theme.name" @click="themeId = theme.id"><Check v-if="themeId === theme.id" :size="17" /></button>
          </div>
      </section>
      <section class="icon-setting">
        <span>账本图标</span>
        <LedgerIconPicker v-model="iconKey" />
      </section>
      <button class="save-ledger-settings" type="submit" :disabled="saving || !name.trim()"><Check :size="19" />{{ saving ? "保存中" : "保存设置" }}</button>
    </form>
  </main>
</template>

<style scoped>
.ledger-settings-shell { background:#f5f8f7; }
.settings-appbar { height:58px; display:grid; grid-template-columns:44px 1fr 44px; align-items:center; border-bottom:1px solid #dce7e4; padding:0 12px; background:#fff; }
.settings-appbar button { width:42px; height:42px; display:grid; place-items:center; border:0; border-radius:8px; background:transparent; color:#31504a; }
.settings-appbar strong { text-align:center; font-size:17px; }
.settings-form { height:calc(100% - 58px); overflow-y:auto; padding:14px 16px 100px; }
.settings-form section { border-top:1px solid #dce7e4; border-bottom:1px solid #dce7e4; padding:0 14px; background:#fff; }
.settings-form label { min-height:66px; display:grid; gap:4px; border-bottom:1px solid #e5edeb; padding:9px 0; }
.settings-form label:last-child { border-bottom:0; }
.settings-form label span,.color-setting > span { color:#7b8884; font-size:11px; }
.settings-form input,.settings-form select { width:100%; border:0; padding:0; outline:0; background:transparent; color:#26342f; font-size:15px; }
.color-setting { margin-top:12px; padding-top:14px!important; padding-bottom:16px!important; }
.icon-setting { margin-top:12px; padding:14px!important; }
.icon-setting > span { display:block; margin-bottom:12px; color:#7b8884; font-size:11px; }
.color-setting > div { display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:7px; width:100%; margin-top:12px; }
.color-setting button { width:100%; aspect-ratio:1; display:grid; place-items:center; border:3px solid #fff; border-radius:9px; color:#fff; box-shadow:0 0 0 1px #d8e4e1; }
.color-setting button.active { box-shadow:0 0 0 2px #263b36; }
.save-ledger-settings { position:absolute; right:16px; bottom:16px; left:16px; height:48px; display:flex; align-items:center; justify-content:center; gap:7px; border:0; border-radius:8px; background:#087f72; color:#fff; font-weight:720; }
.save-ledger-settings:disabled { opacity:.55; }
</style>
