<template>
  <view :class="['medication-page', elderClass]">
    <text class="page-title">用药提醒</text>

    <Loading v-if="loading" text="加载中..." />

    <template v-else>
      <view class="reminder-list">
        <view
          v-for="r in reminders" :key="r.id"
          :class="['reminder-card', !r.is_active ? 'disabled' : '']"
        >
          <view class="reminder-avatar">
            <text class="reminder-avatar-text">{{ nameInitial(r.medication_name) }}</text>
          </view>
          <view class="reminder-info">
            <text class="reminder-name">{{ r.medication_name }}</text>
            <text class="reminder-dosage">
              {{ r.dosage || '-' }} | {{ r.reminder_times?.join(', ') || '-' }}
            </text>
          </view>
          <view class="reminder-actions">
            <view
              :class="['toggle', r.is_active ? 'on' : 'off']"
              @tap="handleToggle(r)"
            >
              <view class="toggle-dot" />
            </view>
            <text class="delete-btn" @tap="handleDelete(r)">删除</text>
          </view>
        </view>
      </view>

      <EmptyState v-if="reminders.length === 0" text="暂无用药提醒" />

      <view v-if="showForm" class="form-card">
        <text class="form-card-title">添加提醒</text>
        <view class="form-item">
          <text class="form-label">药品名称</text>
          <input
            class="form-input"
            placeholder="请输入药品名称"
            placeholder-class="form-placeholder"
            :value="formName"
            @input="formName = ($event as any).detail.value"
          />
        </view>
        <view class="form-item">
          <text class="form-label">剂量</text>
          <input
            class="form-input"
            placeholder="如: 1片、10ml"
            placeholder-class="form-placeholder"
            :value="formDosage"
            @input="formDosage = ($event as any).detail.value"
          />
        </view>
        <view class="form-item">
          <text class="form-label">提醒时间</text>
          <picker mode="time" :value="formTime" @change="formTime = ($event as any).detail.value">
            <view class="time-picker-wrap">
              <text class="time-value">{{ formTime }}</text>
              <text class="time-modify">修改</text>
            </view>
          </picker>
        </view>
        <view class="form-actions">
          <view class="form-cancel" @tap="showForm = false">
            <text class="form-cancel-text">取消</text>
          </view>
          <view class="form-confirm" @tap="handleAdd">
            <text class="form-confirm-text">确认</text>
          </view>
        </view>
      </view>

      <view v-if="!showForm" class="add-btn" @tap="showForm = true">
        <text class="add-text">添加提醒</text>
      </view>
    </template>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onMounted } from 'vue'
import {
  listReminders,
  createReminder,
  updateReminder,
  deleteReminder,
  type MedicationReminder,
} from '@/services/medication-reminder'
import { useAuthStore } from '@/stores/auth'
import { useElderClass } from '@/composables/useElderClass'
import EmptyState from '@/components/EmptyState.vue'
import Loading from '@/components/Loading.vue'

const { elderClass } = useElderClass()
const authStore = useAuthStore()
const reminders = ref<MedicationReminder[]>([])
const loading = ref(true)
const showForm = ref(false)
const formName = ref('')
const formDosage = ref('')
const formTime = ref('08:00')

const fetchReminders = async () => {
  try {
    const res = await listReminders()
    reminders.value = res.data ?? []
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

const handleToggle = async (r: MedicationReminder) => {
  try {
    await updateReminder(r.id, { is_active: !r.is_active, version: r.version })
    fetchReminders()
  } catch {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

const handleDelete = (r: MedicationReminder) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个提醒吗？',
  }).then(async (res) => {
    if (res.confirm) {
      try {
        await deleteReminder(r.id, r.version)
        uni.showToast({ title: '已删除', icon: 'success' })
        fetchReminders()
      } catch {
        uni.showToast({ title: '删除失败', icon: 'none' })
      }
    }
  })
}

const handleAdd = async () => {
  if (!formName.value.trim()) {
    uni.showToast({ title: '请输入药品名称', icon: 'none' })
    return
  }
  const patientId = authStore.currentPatient?.id
  if (!patientId) {
    uni.showToast({ title: '请先绑定患者档案', icon: 'none' })
    return
  }
  try {
    await createReminder({
      patient_id: patientId,
      medication_name: formName.value.trim(),
      dosage: formDosage.value.trim() || undefined,
      reminder_times: [formTime.value],
      is_active: true,
    })
    formName.value = ''
    formDosage.value = ''
    formTime.value = '08:00'
    showForm.value = false
    uni.showToast({ title: '添加成功', icon: 'success' })
    fetchReminders()
  } catch {
    uni.showToast({ title: '添加失败', icon: 'none' })
  }
}

const nameInitial = (name: string) => {
  return name ? name.charAt(0) : '药'
}

onMounted(() => { fetchReminders() })
</script>

<style lang="scss" scoped>
.medication-page { min-height: 100vh; background: $bg; padding: 32px 24px; padding-bottom: 160px; }
.page-title { @include section-title; padding-left: 4px; }
.reminder-list { display: flex; flex-direction: column; gap: 16px; }
.reminder-card {
  display: flex;
  align-items: center;
  background: $card;
  border-radius: $r;
  padding: 24px;
  box-shadow: $shadow-sm;
  &.disabled { opacity: 0.55; }
}
.reminder-avatar {
  @include flex-center;
  width: 72px; height: 72px;
  border-radius: $r;
  background: $acc-l;
  flex-shrink: 0;
  margin-right: 20px;
}
.reminder-avatar-text {
  font-family: 'Georgia', 'Times New Roman', serif;
  font-size: var(--tk-font-num);
  font-weight: bold;
  color: $acc;
}
.reminder-info { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.reminder-name {
  font-family: 'Georgia', 'Times New Roman', serif;
  font-size: var(--tk-font-num);
  font-weight: bold;
  color: $tx;
  margin-bottom: 4px;
}
.reminder-dosage {
  @include serif-number;
  font-size: var(--tk-font-h2);
  color: $tx2;
}
.reminder-actions { display: flex; align-items: center; gap: 16px; flex-shrink: 0; margin-left: 12px; }
.toggle {
  width: 84px; height: 48px;
  border-radius: $r-pill;
  padding: 4px;
  position: relative;
  transition: background 0.3s;
  &.on { background: $pri; }
  &.off { background: $bd; }
}
.toggle-dot {
  width: 40px; height: 40px;
  border-radius: 50%;
  background: $card;
  position: absolute;
  top: 4px;
  transition: left 0.3s;
  .toggle.on & { left: 40px; }
  .toggle.off & { left: 4px; }
}
.delete-btn {
  font-size: var(--tk-font-h2);
  color: $dan;
  padding: 14px 16px;
  min-height: 48px;
  @include flex-center;
}
.form-card { background: $card; border-radius: $r; padding: 28px; margin-top: 24px; box-shadow: $shadow-sm; }
.form-card-title {
  font-family: 'Georgia', 'Times New Roman', serif;
  font-size: var(--tk-font-body-lg);
  font-weight: bold;
  color: $tx;
  margin-bottom: 20px;
  display: block;
}
.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 0;
  border-bottom: 1px solid $bd-l;
  &:last-of-type { border-bottom: none; }
}
.form-label { font-size: var(--tk-font-body-lg); color: $tx; flex-shrink: 0; width: 160px; }
.form-input { flex: 1; font-size: var(--tk-font-body-lg); color: $tx; text-align: right; border: none; background: transparent; outline: none; }
.form-placeholder { color: $tx3; }
.time-picker-wrap { flex: 1; display: flex; align-items: center; justify-content: flex-end; gap: 12px; }
.time-value { @include serif-number; font-size: var(--tk-font-body-lg); color: $tx; }
.time-modify { font-size: var(--tk-font-h2); color: $pri; }
.form-actions { display: flex; gap: 16px; margin-top: 24px; }
.form-cancel { flex: 1; background: $bd-l; border-radius: $r-sm; padding: 20px; text-align: center; }
.form-cancel-text { font-size: var(--tk-font-body-lg); color: $tx2; }
.form-confirm { flex: 1; background: $pri; border-radius: $r-sm; padding: 20px; text-align: center; }
.form-confirm-text { font-size: var(--tk-font-body-lg); color: $white; font-weight: bold; }
.add-btn {
  position: fixed;
  bottom: 0; left: 0; right: 0;
  background: $pri;
  padding: 28px;
  text-align: center;
  box-shadow: 0 -2px 12px rgba(196, 98, 58, 0.15);
}
.add-text {
  font-family: 'Georgia', 'Times New Roman', serif;
  font-size: var(--tk-font-num);
  color: $white;
  font-weight: bold;
  letter-spacing: 2px;
}
</style>
