interface MedicineForm {
  name: string;
  category: string;
  dosage: string;
  frequency: string;
  slots: string[];
  quantity: number;
  unit: string;
  expiryDate: string;
  notes: string;
}

const STORAGE_KEY = 'medicine_box_list';
const FREQ_SLOTS: Record<string, string[]> = {
  '每日1次': ['早'],
  '每日2次': ['早', '晚'],
  '每日3次': ['早', '中', '晚'],
  '每日4次': ['早', '中', '晚', '睡前'],
  '每周1次': ['自定义'],
  '按需服用': ['按需'],
};

Page({
  data: {
    editId: '',
    categories: ['抗生素', '解热镇痛', '心血管', '降糖药', '消化系统', '抗过敏', '维生素', '中成药', '外用', '其他'],
    frequencies: ['每日1次', '每日2次', '每日3次', '每日4次', '每周1次', '按需服用'],
    units: ['盒', '瓶', '片', '粒', '支', '包', '袋'],
    timeSlots: ['早', '中', '晚', '睡前', '按需'],
    categoryIndex: -1,
    freqIndex: -1,
    unitIndex: -1,
    today: '',
    form: {
      name: '',
      category: '',
      dosage: '',
      frequency: '',
      slots: [] as string[],
      quantity: 1,
      unit: '',
      expiryDate: '',
      notes: '',
    } as MedicineForm,
  },

  onLoad(options: Record<string, string>) {
    const today = new Date();
    this.setData({
      today: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`,
      editId: options.id || '',
    });

    if (options.id) {
      const list: any[] = wx.getStorageSync(STORAGE_KEY) || [];
      const item = list.find((m: any) => m.id === options.id);
      if (item) {
        const form = {
          name: item.name,
          category: item.category,
          dosage: item.dosage,
          frequency: item.frequency,
          slots: item.slots || [],
          quantity: item.quantity,
          unit: item.unit,
          expiryDate: item.expiryDate,
          notes: item.notes || '',
        };
        this.setData({
          form,
          categoryIndex: this.data.categories.indexOf(item.category),
          freqIndex: this.data.frequencies.indexOf(item.frequency),
          unitIndex: this.data.units.indexOf(item.unit),
        });
      }
    }
  },

  onFieldChange(e: WechatMiniprogram.Input) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`form.${field}`]: e.detail.value });
  },

  onCategoryChange(e: WechatMiniprogram.PickerChange) {
    const idx = Number(e.detail.value);
    this.setData({ categoryIndex: idx, 'form.category': this.data.categories[idx] });
  },

  onFreqChange(e: WechatMiniprogram.PickerChange) {
    const idx = Number(e.detail.value);
    const freq = this.data.frequencies[idx];
    const slots = FREQ_SLOTS[freq] || ['早', '中', '晚'];
    this.setData({ freqIndex: idx, 'form.frequency': freq, 'form.slots': slots });
  },

  onUnitChange(e: WechatMiniprogram.PickerChange) {
    const idx = Number(e.detail.value);
    this.setData({ unitIndex: idx, 'form.unit': this.data.units[idx] });
  },

  onDateChange(e: WechatMiniprogram.PickerChange) {
    this.setData({ 'form.expiryDate': e.detail.value });
  },

  toggleSlot(e: WechatMiniprogram.TouchEvent) {
    const { slot } = e.currentTarget.dataset;
    const slots = [...this.data.form.slots];
    const idx = slots.indexOf(slot);
    if (idx > -1) {
      slots.splice(idx, 1);
    } else {
      slots.push(slot);
    }
    this.setData({ 'form.slots': slots });
  },

  save() {
    const { form, editId } = this.data;
    if (!form.name.trim()) {
      wx.showToast({ title: '请输入药品名称', icon: 'none' });
      return;
    }
    if (!form.category) {
      wx.showToast({ title: '请选择药品分类', icon: 'none' });
      return;
    }

    const list: any[] = wx.getStorageSync(STORAGE_KEY) || [];

    if (editId) {
      const idx = list.findIndex((m: any) => m.id === editId);
      if (idx > -1) {
        list[idx] = { ...list[idx], ...form };
      }
    } else {
      list.unshift({
        id: Date.now().toString(),
        ...form,
        addedAt: new Date().toISOString().split('T')[0],
      });
    }

    wx.setStorageSync(STORAGE_KEY, list);
    wx.showToast({ title: editId ? '已更新' : '已添加', icon: 'success' });
    setTimeout(() => wx.navigateBack(), 800);
  },

  cancel() {
    const { editId } = this.data;
    if (!editId) {
      wx.navigateBack();
      return;
    }
    wx.showModal({
      title: '确认删除',
      content: '将删除此药品及打卡记录',
      success: (res) => {
        if (res.confirm) {
          const list: any[] = wx.getStorageSync(STORAGE_KEY) || [];
          wx.setStorageSync(STORAGE_KEY, list.filter((m: any) => m.id !== editId));
          const checkins = wx.getStorageSync('checkin_records') || {};
          delete checkins[editId];
          wx.setStorageSync('checkin_records', checkins);
          wx.showToast({ title: '已删除', icon: 'success' });
          setTimeout(() => wx.navigateBack(), 800);
        }
      },
    });
  },
});
