<template>
  <div class="body-layout">
    <!-- Sub tabs -->
    <div class="sub-tabs">
      <button class="sub-tab" :class="{ active: subTab === 'health' }" @click="subTab = 'health'">健康打卡</button>
      <button class="sub-tab" :class="{ active: subTab === 'sleep' }" @click="subTab = 'sleep'">睡眠</button>
      <button class="sub-tab" :class="{ active: subTab === 'gym' }" @click="subTab = 'gym'">健身</button>
      <button class="sub-tab" :class="{ active: subTab === 'period' }" @click="subTab = 'period'">经期</button>
    </div>

    <!-- 健康打卡 -->
    <div v-if="subTab === 'health'" class="health-section">
      <div class="section-header">
        <h3>今日打卡</h3>
        <span class="date-label">{{ today }}</span>
      </div>
      <div class="checkin-grid">
        <div
          v-for="item in todayPlanItems('health')"
          :key="item.id"
          class="checkin-item"
          :class="{ checked: isChecked('health', item.id) }"
          @click="toggleCheck('health', item.id)"
        >
          <span class="checkin-check">{{ isChecked('health', item.id) ? '✅' : '⬜' }}</span>
          <span>{{ item.name }}</span>
        </div>
        <div v-if="todayPlanItems('health').length === 0" class="empty-hint">
          还没有设定本月计划，从下方选择项目添加
        </div>
      </div>

      <div class="section-header">
        <h3>物品池</h3>
      </div>
      <div class="pool-items">
        <div v-for="item in store.healthItems" :key="item.id" class="pool-item">
          <span @click="togglePlanItem('health', item.id)">
            {{ isPlanItem('health', item.id) ? '✓' : '+' }} {{ item.name }}
          </span>
          <button class="remove-btn" @click="store.deleteHealthItem(item.id)">✕</button>
        </div>
      </div>
      <div class="add-row">
        <input v-model="newHealthItem" placeholder="添加新项目" @keydown.enter.prevent="addItem('health')">
        <button class="btn btn-accent" @click="addItem('health')">+</button>
      </div>
    </div>

    <!-- 睡眠 -->
    <div v-if="subTab === 'sleep'" class="sleep-section">
      <div class="section-header">
        <h3>睡眠记录</h3>
      </div>
      <div class="capture-row" style="margin-bottom: 16px;">
        <input
          class="capture-input"
          v-model="sleepInput"
          placeholder="昨晚10:30 / 25号 9点半"
          @keydown.enter.prevent="addSleepRecord"
        >
        <button class="btn btn-accent" @click="addSleepRecord">记录</button>
      </div>
      <div class="sleep-hint" v-if="sleepHint">{{ sleepHint }}</div>

      <h4 style="margin: 16px 0 8px; color: #888; font-size: 14px;">记录明细</h4>
      <table class="data-table" v-if="store.sleepRecords.length">
        <thead><tr><th>日期</th><th>入睡时间</th><th></th></tr></thead>
        <tbody>
          <tr v-for="r in store.sleepRecords" :key="r.date">
            <td>{{ r.date }}</td>
            <td>{{ r.time }}</td>
            <td><button class="remove-btn" @click="store.deleteSleep(r.date)">✕</button></td>
          </tr>
        </tbody>
      </table>
      <div v-else class="empty-hint">还没有睡眠记录</div>
    </div>

    <!-- 健身 -->
    <div v-if="subTab === 'gym'" class="gym-section">
      <div class="section-header">
        <h3>💪 健身记录</h3>
        <button class="btn btn-accent" @click="showGymForm = true">+ 记录</button>
      </div>
      <div v-for="r in store.gymRecords" :key="r.id" class="record-card">
        <div><strong>{{ r.date }}</strong> {{ r.type }} {{ r.duration }}</div>
        <div v-if="r.note" class="record-note">{{ r.note }}</div>
        <button class="remove-btn" @click="store.deleteGym(r.id)">✕</button>
      </div>
      <div v-if="showGymForm" class="edit-form">
        <input v-model="gymDate" type="date">
        <input v-model="gymType" placeholder="运动类型">
        <input v-model="gymDuration" placeholder="时长">
        <input v-model="gymNote" placeholder="备注">
        <div class="edit-actions">
          <button class="btn btn-close" @click="showGymForm = false">取消</button>
          <button class="btn btn-accent" @click="saveGym">保存</button>
        </div>
      </div>
    </div>

    <!-- 经期 -->
    <div v-if="subTab === 'period'" class="period-section">
      <div class="section-header">
        <h3>🌸 经期记录</h3>
        <button class="btn btn-accent" @click="showPeriodForm = true">+ 记录</button>
      </div>
      <div v-for="r in store.periodRecords" :key="r.id" class="record-card">
        <div><strong>{{ r.start_date }}</strong> {{ r.end_date ? '→ ' + r.end_date : '进行中' }}</div>
        <div v-if="r.note" class="record-note">{{ r.note }}</div>
        <button class="remove-btn" @click="store.deletePeriod(r.id)">✕</button>
      </div>
      <div v-if="showPeriodForm" class="edit-form">
        <label>开始日期</label>
        <input v-model="periodStart" type="date">
        <label>结束日期</label>
        <input v-model="periodEnd" type="date">
        <input v-model="periodNote" placeholder="备注">
        <div class="edit-actions">
          <button class="btn btn-close" @click="showPeriodForm = false">取消</button>
          <button class="btn btn-accent" @click="savePeriod">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { usePlannerStore } from '../stores/planner'

const store = usePlannerStore()
const subTab = ref('health')

const today = computed(() => {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
})
const currentMonth = computed(() => today.value.slice(0, 7))

function uid() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 7) }

// ---- Health check-in ----
const newHealthItem = ref('')

function todayPlanItems(type) {
  const plans = type === 'music' ? store.musicPlans : store.healthPlans
  const items = type === 'music' ? store.musicItems : store.healthItems
  const plan = plans.find(p => p.month === currentMonth.value && p.type === type)
  if (!plan) return []
  const ids = JSON.parse(plan.item_ids || '[]')
  return items.filter(i => ids.includes(i.id))
}

function isChecked(type, itemId) {
  const checks = type === 'music' ? store.musicChecks : store.healthChecks
  return checks.some(c => c.date === today.value && c.type === type && c.item_id === itemId)
}

async function toggleCheck(type, itemId) {
  const checked = isChecked(type, itemId)
  await store.toggleHealthCheck({ date: today.value, type, item_id: itemId, checked: checked ? 0 : 1 })
}

function isPlanItem(type, itemId) {
  const plans = type === 'music' ? store.musicPlans : store.healthPlans
  const plan = plans.find(p => p.month === currentMonth.value && p.type === type)
  if (!plan) return false
  return JSON.parse(plan.item_ids || '[]').includes(itemId)
}

async function togglePlanItem(type, itemId) {
  const plans = type === 'music' ? store.musicPlans : store.healthPlans
  const plan = plans.find(p => p.month === currentMonth.value && p.type === type) || {
    month: currentMonth.value, type, item_ids: '[]'
  }
  const ids = JSON.parse(plan.item_ids || '[]')
  const idx = ids.indexOf(itemId)
  if (idx >= 0) ids.splice(idx, 1)
  else ids.push(itemId)
  await store.saveHealthPlan({ month: currentMonth.value, type, item_ids: JSON.stringify(ids) })
}

async function addItem(type) {
  const name = type === 'music' ? newMusicItem.value.trim() : newHealthItem.value.trim()
  if (!name) return
  await store.addHealthItem({ id: uid(), name, type })
  if (type === 'music') newMusicItem.value = ''
  else newHealthItem.value = ''
}

// ---- Sleep ----
const sleepInput = ref('')
const sleepHint = ref('')

function parseSleepTime(text) {
  // Simple parser: "10:30" or "昨晚10点半"
  const timeMatch = text.match(/(\d{1,2}):(\d{2})/)
  if (timeMatch) return `${timeMatch[1].padStart(2, '0')}:${timeMatch[2]}`
  const cnMatch = text.match(/(\d{1,2})点半?/)
  if (cnMatch) {
    const h = parseInt(cnMatch[0])
    const m = text.includes('半') ? '30' : '00'
    return `${String(h).padStart(2, '0')}:${m}`
  }
  return null
}

async function addSleepRecord() {
  const text = sleepInput.value.trim()
  if (!text) return
  const time = parseSleepTime(text)
  if (!time) {
    sleepHint.value = '无法识别时间，请输入如 10:30 或 10点半'
    return
  }
  // Default to yesterday if late night
  const now = new Date()
  let date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
  const dateMatch = text.match(/(\d{1,2})号/)
  if (dateMatch) {
    date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${dateMatch[1].padStart(2, '0')}`
  }
  await store.addSleep({ date, time })
  sleepInput.value = ''
  sleepHint.value = `已记录 ${date} ${time}`
}

// ---- Gym ----
const showGymForm = ref(false)
const gymDate = ref(new Date().toISOString().slice(0, 10))
const gymType = ref('')
const gymDuration = ref('')
const gymNote = ref('')

async function saveGym() {
  await store.addGym({ id: uid(), date: gymDate.value, type: gymType.value, duration: gymDuration.value, note: gymNote.value })
  showGymForm.value = false
  gymType.value = ''
  gymDuration.value = ''
  gymNote.value = ''
}

// ---- Period ----
const showPeriodForm = ref(false)
const periodStart = ref('')
const periodEnd = ref('')
const periodNote = ref('')
const newMusicItem = ref('')

async function savePeriod() {
  if (!periodStart.value) return
  await store.addPeriod({ id: uid(), start_date: periodStart.value, end_date: periodEnd.value || null, note: periodNote.value })
  showPeriodForm.value = false
  periodStart.value = ''
  periodEnd.value = ''
  periodNote.value = ''
}
</script>
