// 用药管理页 - 全栈版本
function MedicationPage({ navigate, goBack }) {
  const { state, dispatch, showToast } = React.useContext(AppContext);
  const { medications } = state;

  const [sheetVisible, setSheetVisible] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const [form, setForm] = React.useState({
    name: '', dose: '', frequency: '每日1次', times: ['早'], note: ''
  });
  const [saving, setSaving] = React.useState(false);

  const frequencies = ['每日1次', '每日2次', '每日3次', '按需'];
  const timeOptions = ['早', '中', '晚', '睡前'];

  const openAdd = () => {
    setEditingId(null);
    setForm({ name: '', dose: '', frequency: '每日1次', times: ['早'], note: '' });
    setSheetVisible(true);
  };

  const openEdit = (med) => {
    setEditingId(med.id);
    setForm({ ...med });
    setSheetVisible(true);
  };

  const handleSave = async () => {
    if (saving) return;
    if (!form.name.trim()) {
      showToast('请输入药品名称');
      return;
    }
    if (!form.dose.trim()) {
      showToast('请输入剂量');
      return;
    }

    setSaving(true);
    try {
      if (editingId) {
        const updated = await api.updateMedication(editingId, form);
        dispatch({
          type: 'UPDATE_MEDICATION_LOCAL',
          payload: { id: editingId, data: updated }
        });
        showToast('已更新');
      } else {
        const newItem = await api.addMedication(form);
        dispatch({ type: 'ADD_MEDICATION_LOCAL', payload: newItem });
        showToast('已添加用药');
      }
      setSheetVisible(false);
    } catch (err) {
      showToast(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('确定要删除这条用药记录吗？')) return;
    try {
      await api.deleteMedication(id);
      dispatch({ type: 'DELETE_MEDICATION_LOCAL', payload: id });
      showToast('已删除');
    } catch (err) {
      showToast(err.message);
    }
  };

  const toggleTime = (t) => {
    setForm(prev => ({
      ...prev,
      times: prev.times.includes(t)
        ? prev.times.filter(x => x !== t)
        : [...prev.times, t]
    }));
  };

  const onFrequencyChange = (freq) => {
    let newTimes = [...form.times];
    if (freq === '每日1次') newTimes = newTimes.length ? [newTimes[0]] : ['早'];
    else if (freq === '每日2次') {
      if (newTimes.length < 2) newTimes = ['早', '晚'];
    } else if (freq === '每日3次') {
      if (newTimes.length < 3) newTimes = ['早', '中', '晚'];
    } else {
      newTimes = [];
    }
    setForm(prev => ({ ...prev, frequency: freq, times: newTimes }));
  };

  return (
    <div className="page page-enter">
      <TopBar title="用药管理" onBack={goBack} />

      <div style={{ padding: '0 16px' }}>
        <div style={{
          background: 'linear-gradient(135deg, #4a7dac 0%, #6fa5d0 100%)',
          borderRadius: 16,
          padding: '18px 20px',
          color: '#fff',
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}>
          <div>
            <div style={{ fontSize: 13, opacity: 0.85 }}>在用药物</div>
            <div style={{ fontSize: 32, fontWeight: 700, marginTop: 2 }}>
              {medications.length}<span style={{ fontSize: 14, fontWeight: 400, marginLeft: 4 }}>种</span>
            </div>
          </div>
          <div style={{
            width: 52, height: 52, borderRadius: 14,
            background: 'rgba(255,255,255,0.2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon.Pill color="#fff" size={26} />
          </div>
        </div>

        <div className="card">
          <div className="card-title">
            <span>我的用药</span>
          </div>
          {medications.length === 0 ? (
            <div className="empty-state">
              <div className="empty-state-icon">💊</div>
              <div className="empty-state-text">还没有录入用药信息</div>
            </div>
          ) : (
            medications.map(m => (
              <div key={m.id} style={{
                display: 'flex',
                alignItems: 'flex-start',
                gap: 12,
                padding: '14px 0',
                borderBottom: medications.indexOf(m) < medications.length - 1 ? '1px solid #f0ebe0' : 'none',
              }}>
                <div style={{
                  width: 44, height: 44, borderRadius: 12,
                  background: '#e8f0f7',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                  marginTop: 2,
                }}>
                  <Icon.Pill color="#4a7dac" size={20} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: '#2c3e3a' }}>
                    {m.name}
                    <span style={{ fontSize: 12, color: '#8a9390', fontWeight: 400, marginLeft: 6 }}>
                      {m.dose}
                    </span>
                  </div>
                  <div style={{ fontSize: 12, color: '#5a6e69', marginTop: 4, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    <span className="chip chip-info">{m.frequency}</span>
                    {m.times && m.times.length > 0 && (
                      <span className="chip chip-neutral">{m.times.join(' / ')}</span>
                    )}
                  </div>
                  {m.note && (
                    <div style={{ fontSize: 12, color: '#a3a89f', marginTop: 6 }}>
                      💡 {m.note}
                    </div>
                  )}
                </div>
                <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                  <button
                    className="btn btn-secondary btn-sm"
                    style={{ padding: '4px 10px' }}
                    onClick={() => openEdit(m)}
                  >
                    <Icon.Edit size={14} />
                  </button>
                  <button
                    className="btn btn-danger btn-sm"
                    style={{ padding: '4px 10px' }}
                    onClick={() => handleDelete(m.id)}
                  >
                    <Icon.Trash size={14} />
                  </button>
                </div>
              </div>
            ))
          )}
        </div>

        <div style={{
          background: '#fef4e6',
          borderRadius: 12,
          padding: '12px 16px',
          fontSize: 12,
          color: '#8a7650',
          lineHeight: 1.6,
          marginBottom: 14,
        }}>
          <div style={{ fontWeight: 600, marginBottom: 4 }}>📌 温馨提示</div>
          <div>请遵医嘱按时服药，不要自行调整剂量或停药。如有不适请及时就医。</div>
        </div>
      </div>

      <button className="fab" onClick={openAdd}>
        <Icon.Plus color="#fff" size={26} />
      </button>

      <BottomSheet
        visible={sheetVisible}
        title={editingId ? '编辑用药' : '新增用药'}
        onClose={() => setSheetVisible(false)}
      >
        <div className="form-group">
          <label className="form-label">药品名称</label>
          <input
            className="form-input"
            type="text"
            placeholder="如：氨氯地平片"
            value={form.name}
            onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))}
          />
        </div>

        <div className="form-group">
          <label className="form-label">剂量</label>
          <input
            className="form-input"
            type="text"
            placeholder="如：5mg / 0.5g"
            value={form.dose}
            onChange={e => setForm(prev => ({ ...prev, dose: e.target.value }))}
          />
        </div>

        <div className="form-group">
          <label className="form-label">服用频次</label>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {frequencies.map(f => (
              <button
                key={f}
                style={{
                  padding: '8px 14px',
                  borderRadius: 8,
                  fontSize: 13,
                  border: `1.5px solid ${form.frequency === f ? '#3a8f7a' : '#ebe8e0'}`,
                  background: form.frequency === f ? '#eef5f2' : '#fff',
                  color: form.frequency === f ? '#3a8f7a' : '#5a6e69',
                  fontWeight: form.frequency === f ? 500 : 400,
                }}
                onClick={() => onFrequencyChange(f)}
              >
                {f}
              </button>
            ))}
          </div>
        </div>

        <div className="form-group">
          <label className="form-label">服用时间</label>
          <div style={{ display: 'flex', gap: 8 }}>
            {timeOptions.map(t => (
              <button
                key={t}
                style={{
                  flex: 1,
                  padding: '10px 0',
                  borderRadius: 8,
                  fontSize: 13,
                  border: `1.5px solid ${form.times.includes(t) ? '#3a8f7a' : '#ebe8e0'}`,
                  background: form.times.includes(t) ? '#eef5f2' : '#fff',
                  color: form.times.includes(t) ? '#3a8f7a' : '#5a6e69',
                  fontWeight: form.times.includes(t) ? 500 : 400,
                }}
                onClick={() => toggleTime(t)}
              >
                {t}
              </button>
            ))}
          </div>
          <div className="form-hint">可多选</div>
        </div>

        <div className="form-group">
          <label className="form-label">备注（选填）</label>
          <textarea
            className="form-input"
            placeholder="如：早餐后服用、避免与XX同服等"
            value={form.note}
            onChange={e => setForm(prev => ({ ...prev, note: e.target.value }))}
          />
        </div>

        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
          {saving ? '保存中...' : (editingId ? '保存修改' : '确认添加')}
        </button>
      </BottomSheet>
    </div>
  );
}
