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

const MED_KEY = 'medicine_box_list';
const CHECKIN_KEY = 'checkin_records';

function getToday(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function formatDate(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function daysUntil(dateStr: string): number {
  const now = new Date();
  now.setHours(0, 0, 0, 0);
  const target = new Date(dateStr);
  target.setHours(0, 0, 0, 0);
  return Math.ceil((target.getTime() - now.getTime()) / 86400000);
}

Page({
  data: {
    activeTab: 0, // 0=库存 1=打卡
    medicines: [] as Medicine[],
    totalCount: 0,
    expiringCount: 0,
    lowStockCount: 0,
    expiringItems: [] as string[],

    // Check-in
    today: '',
    todayStr: '',
    checkSlots: [] as { label: string; time: string; medicines: any[]; allChecked: boolean }[],
    checkProgress: 0,
    checkTotal: 0,
    checkDone: 0,
    weekDays: [] as { date: string; day: string; isToday: boolean; done: number; total: number }[],
  },

  onLoad() {
    this.loadData();
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({ selected: 0 });
    }
    this.loadData();
  },

  loadData() {
    const medicines: Medicine[] = wx.getStorageSync(MED_KEY) || [];
    const totalCount = medicines.length;
    const expiringItems = medicines.filter((m) => {
      const d = daysUntil(m.expiryDate);
      return d >= 0 && d <= 90;
    });
    const lowStockCount = medicines.filter((m) => m.quantity <= 5).length;

    // Week calendar
    const today = new Date();
    const weekDays: any[] = [];
    for (let i = 3; i >= 0; i--) {
      const d = new Date(today);
      d.setDate(d.getDate() - i);
      const ds = formatDate(d);
      const dayNames = ['日', '一', '二', '三', '四', '五', '六'];
      weekDays.push({ date: ds, day: dayNames[d.getDay()], isToday: i === 0, done: 0, total: 0 });
    }

    // Check-in data
    const todayStr = getToday();
    const checkinData: Record<string, Record<string, string[]>> = wx.getStorageSync(CHECKIN_KEY) || {};
    const todayCheckin = checkinData[todayStr] || {};

    // Build check-in slots
    const slotDefs = [
      { label: '早', time: '早晨 (6:00-9:00)' },
      { label: '中', time: '中午 (11:00-14:00)' },
      { label: '晚', time: '晚上 (17:00-21:00)' },
      { label: '睡前', time: '睡前 (21:00-23:00)' },
    ];

    let checkTotal = 0;
    let checkDone = 0;

    const checkSlots = slotDefs.map((sd) => {
      const slotMeds = medicines
        .filter((m) => m.slots && m.slots.includes(sd.label))
        .map((m) => {
          const checked = (todayCheckin[m.id] || []).includes(sd.label);
          return {
            id: m.id,
            name: m.name,
            dosage: m.dosage,
            category: m.category,
            checked,
          };
        });
      checkTotal += slotMeds.length;
      const slotDone = slotMeds.filter((m) => m.checked).length;
      checkDone += slotDone;
      return { label: sd.label, time: sd.time, medicines: slotMeds, allChecked: slotMeds.length > 0 && slotDone === slotMeds.length };
    });

    // Populate week day stats
    const updatedWeekDays = weekDays.map((wd) => {
      const dayCheckin = checkinData[wd.date] || {};
      let total = 0;
      let done = 0;
      medicines.forEach((m) => {
        const slots = m.slots || [];
        total += slots.length;
        const checkedSlots = dayCheckin[m.id] || [];
        done += slots.filter((s: string) => checkedSlots.includes(s)).length;
      });
      return { ...wd, total, done };
    });

    this.setData({
      medicines,
      totalCount,
      expiringCount: expiringItems.length,
      expiringItems: expiringItems.map((m) => m.name),
      lowStockCount,
      today: todayStr,
      todayStr: `${today.getFullYear()}年${today.getMonth() + 1}月${today.getDate()}日`,
      checkSlots,
      checkTotal,
      checkDone,
      checkProgress: checkTotal > 0 ? Math.round((checkDone / checkTotal) * 100) : 0,
      weekDays: updatedWeekDays,
    });
  },

  switchTab(e: WechatMiniprogram.TouchEvent) {
    const { tab } = e.currentTarget.dataset;
    this.setData({ activeTab: Number(tab) });
  },

  goAdd() {
    wx.navigateTo({ url: '/pages/tab-bar/medicine-box/add/index' });
  },

  goEdit(e: WechatMiniprogram.TouchEvent) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({ url: `/pages/tab-bar/medicine-box/add/index?id=${id}` });
  },

  deleteMedicine(e: WechatMiniprogram.TouchEvent) {
    const { id, name } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: `确定要删除「${name}」吗？`,
      success: (res) => {
        if (res.confirm) {
          const list: Medicine[] = wx.getStorageSync(MED_KEY) || [];
          wx.setStorageSync(MED_KEY, list.filter((m) => m.id !== id));
          // cleanup checkin records
          const checkinData = wx.getStorageSync(CHECKIN_KEY) || {};
          Object.keys(checkinData).forEach((date) => {
            delete checkinData[date][id];
          });
          wx.setStorageSync(CHECKIN_KEY, checkinData);
          wx.showToast({ title: '已删除', icon: 'success' });
          this.loadData();
        }
      },
    });
  },

  toggleCheck(e: WechatMiniprogram.TouchEvent) {
    const { mid, slot } = e.currentTarget.dataset;
    const todayStr = this.data.today;
    const checkinData: Record<string, Record<string, string[]>> = wx.getStorageSync(CHECKIN_KEY) || {};

    if (!checkinData[todayStr]) checkinData[todayStr] = {};
    if (!checkinData[todayStr][mid]) checkinData[todayStr][mid] = [];

    const idx = checkinData[todayStr][mid].indexOf(slot);
    if (idx > -1) {
      checkinData[todayStr][mid].splice(idx, 1);
    } else {
      checkinData[todayStr][mid].push(slot);
    }

    wx.setStorageSync(CHECKIN_KEY, checkinData);
    this.loadData();
  },

  onPrevDay() {
    // For future: navigate to past dates
  },

  onNextDay() {
    // For future: navigate to future dates
  },
});
