<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { api, type Settings } from '../api/request'

const router = useRouter()

const dailyTarget = ref(20)
const masterRequired = ref(3)
const weakThreshold = ref(3)
const loading = ref(true)
const saveState = ref<'idle' | 'saving' | 'success' | 'error'>('idle')
const toast = ref<{ text: string; type: 'success' | 'error' } | null>(null)

let toastTimer: ReturnType<typeof setTimeout> | null = null
let successTimer: ReturnType<typeof setTimeout> | null = null

const saveLabel = computed(() => {
  if (saveState.value === 'saving') return '保存中...'
  if (saveState.value === 'success') return '已保存 ✓'
  return '保存设置'
})

function applySettings(data: Settings) {
  dailyTarget.value = data.daily_target
  masterRequired.value = data.master_required_count
  weakThreshold.value = data.weak_wrong_threshold
}

function showToast(text: string, type: 'success' | 'error') {
  if (toastTimer) clearTimeout(toastTimer)
  toast.value = { text, type }
  toastTimer = setTimeout(() => {
    toast.value = null
  }, 2800)
}

onMounted(async () => {
  try {
    const { data } = await api.getSettings()
    applySettings(data)
  } finally {
    loading.value = false
  }
})

async function save() {
  if (saveState.value === 'saving') return
  saveState.value = 'saving'
  try {
    const { data } = await api.updateSettings({
      daily_target: dailyTarget.value,
      master_required_count: masterRequired.value,
      weak_wrong_threshold: weakThreshold.value,
    })
    applySettings(data)
    saveState.value = 'success'
    showToast('日常积累设置已生效', 'success')
    if (successTimer) clearTimeout(successTimer)
    successTimer = setTimeout(() => {
      if (saveState.value === 'success') saveState.value = 'idle'
    }, 2200)
  } catch {
    saveState.value = 'error'
    showToast('保存失败，请检查网络后重试', 'error')
    setTimeout(() => {
      if (saveState.value === 'error') saveState.value = 'idle'
    }, 2200)
  }
}
</script>

<template>
  <div class="page">
    <div class="header-row">
      <button type="button" class="back-btn" @click="router.back()">返回</button>
      <h1 class="page-title">学习设置</h1>
    </div>
    <p class="page-sub">调整日常积累的每日练习量与学习规则</p>

    <p v-if="loading" class="muted">加载中...</p>
    <template v-else>
      <section class="block">
        <h2 class="block-title">练习参数</h2>
        <p class="block-hint">仅作用于翻译加词与日常积累练习</p>
        <div class="field">
          <label>每日练习量</label>
          <input v-model.number="dailyTarget" type="range" min="1" max="100" step="1" />
          <span class="field-value">{{ dailyTarget }} 词/天</span>
        </div>
        <div class="field">
          <label>连续答对几次算掌握</label>
          <input v-model.number="masterRequired" type="range" min="1" max="20" step="1" />
          <span class="field-value">{{ masterRequired }} 次</span>
        </div>
        <div class="field">
          <label>答错几次标记易错</label>
          <input v-model.number="weakThreshold" type="range" min="1" max="20" step="1" />
          <span class="field-value">{{ weakThreshold }} 次</span>
        </div>
      </section>

      <button
        type="button"
        class="btn save-btn"
        :class="{
          'btn-primary': saveState === 'idle' || saveState === 'saving',
          'save-success': saveState === 'success',
          'save-error': saveState === 'error',
        }"
        :disabled="saveState === 'saving' || saveState === 'success'"
        @click="save"
      >
        {{ saveLabel }}
      </button>
    </template>

    <Transition name="toast">
      <div
        v-if="toast"
        class="toast"
        :class="toast.type"
        role="status"
        aria-live="polite"
      >
        <span class="toast-icon">{{ toast.type === 'success' ? '✓' : '!' }}</span>
        <span class="toast-text">{{ toast.text }}</span>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.header-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 4px;
}
.back-btn {
  border: none;
  background: none;
  color: var(--primary, #4f6ef7);
  font-size: 14px;
  cursor: pointer;
  padding: 0;
}
.page-sub {
  font-size: 13px;
  color: var(--muted);
  margin: 0 0 16px;
}
.muted { color: var(--muted); }
.block {
  margin-bottom: 20px;
}
.block-title {
  font-size: 16px;
  margin: 0 0 6px;
}
.block-hint {
  font-size: 12px;
  color: var(--muted);
  margin: 0 0 12px;
}
.field {
  margin-bottom: 16px;
}
.field label {
  display: block;
  font-size: 14px;
  margin-bottom: 8px;
}
.field input[type='range'] {
  width: 100%;
}
.field-value {
  display: block;
  font-size: 13px;
  color: var(--muted);
  margin-top: 4px;
}
.save-btn {
  width: 100%;
  transition: background 0.25s ease, transform 0.15s ease;
}
.save-btn.save-success {
  background: #4f6ef7;
  color: #fff;
  border: none;
}
.save-btn.save-error {
  background: #fef2f2;
  color: #b91c1c;
  border: 1px solid #fecaca;
}
.toast {
  position: fixed;
  left: 50%;
  bottom: calc(24px + env(safe-area-inset-bottom, 0px));
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 10px;
  max-width: min(360px, calc(100vw - 32px));
  padding: 14px 18px;
  border-radius: 14px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.14);
  z-index: 200;
  font-size: 14px;
}
.toast.success {
  background: #4338ca;
  color: #fff;
}
.toast.error {
  background: #fff;
  color: #b91c1c;
  border: 1px solid #fecaca;
}
.toast-icon {
  flex-shrink: 0;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 700;
}
.toast.success .toast-icon {
  background: rgba(255, 255, 255, 0.2);
}
.toast.error .toast-icon {
  background: #fee2e2;
}
.toast-text {
  line-height: 1.4;
}
.toast-enter-active,
.toast-leave-active {
  transition: opacity 0.25s ease, transform 0.25s ease;
}
.toast-enter-from,
.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(12px);
}
</style>
