// 指标记录页 - 全栈版本
function VitalsPage({ navigate, goBack }) {
  const { state, dispatch, showToast } = React.useContext(AppContext);
  const { bloodPressure, bloodSugar } = state;

  const [activeTab, setActiveTab] = React.useState('bp');
  const [sheetVisible, setSheetVisible] = React.useState(false);
  const [form, setForm] = React.useState({
    systolic: '', diastolic: '', value: '', type: 'fasting'
  });
  const [saving, setSaving] = React.useState(false);

  const openAdd = () => {
    setForm({ systolic: '', diastolic: '', value: '', type: 'fasting' });
    setSheetVisible(true);
  };

  const handleSave = async () => {
    if (saving) return;

    try {
      setSaving(true);
      if (activeTab === 'bp') {
        if (!form.systolic || !form.diastolic) {
          showToast('请输入收缩压和舒张压');
          setSaving(false);
          return;
        }
        const newItem = await api.addBloodPressure({
          systolic: Number(form.systolic),
          diastolic: Number(form.diastolic),
        });
        dispatch({ type: 'ADD_BP_LOCAL', payload: newItem });
      } else {
        if (!form.value) {
          showToast('请输入血糖值');
          setSaving(false);
          return;
        }
        const newItem = await api.addBloodSugar({
          value: Number(form.value),
          type: form.type,
        });
        dispatch({ type: 'ADD_BS_LOCAL', payload: newItem });
      }
      showToast('记录已保存');
      setSheetVisible(false);
    } catch (err) {
      showToast(err.message);
    } finally {
      setSaving(false);
    }
  };

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

  function bpStatus(sys, dia) {
    if (sys >= 160 || dia >= 100) return { label: '重度偏高', color: 'danger' };
    if (sys >= 140 || dia >= 90) return { label: '偏高', color: 'danger' };
    if (sys >= 130 || dia >= 85) return { label: '正常高值', color: 'warning' };
    return { label: '正常', color: 'info' };
  }
  function bsStatus(val, type) {
    if (type === 'fasting') {
      if (val >= 7.0) return { label: '偏高', color: 'danger' };
      if (val >= 6.1) return { label: '偏高限', color: 'warning' };
      return { label: '正常', color: 'info' };
    } else {
      if (val >= 11.1) return { label: '偏高', color: 'danger' };
      if (val >= 7.8) return { label: '偏高限', color: 'warning' };
      return { label: '正常', color: 'info' };
    }
  }

  const list = activeTab === 'bp' ? bloodPressure : bloodSugar;

  return (
    <div className="page page-enter">
      <TopBar title="指标记录" onBack={goBack} />

      <div style={{ padding: '0 16px' }}>
        {/* Tab 切换 */}
        <div style={{
          display: 'flex',
          background: '#f0ebe0',
          borderRadius: 12,
          padding: 4,
          marginBottom: 16,
        }}>
          <button
            style={{
              flex: 1,
              padding: '10px 0',
              borderRadius: 9,
              fontSize: 14,
              fontWeight: activeTab === 'bp' ? 600 : 400,
              color: activeTab === 'bp' ? '#2c3e3a' : '#8a9390',
              background: activeTab === 'bp' ? '#fff' : 'transparent',
              transition: 'all 0.2s',
            }}
            onClick={() => setActiveTab('bp')}
          >
            血压
          </button>
          <button
            style={{
              flex: 1,
              padding: '10px 0',
              borderRadius: 9,
              fontSize: 14,
              fontWeight: activeTab === 'bs' ? 600 : 400,
              color: activeTab === 'bs' ? '#2c3e3a' : '#8a9390',
              background: activeTab === 'bs' ? '#fff' : 'transparent',
              transition: 'all 0.2s',
            }}
            onClick={() => setActiveTab('bs')}
          >
            血糖
          </button>
        </div>

        {/* 最新记录卡片 */}
        {list.length > 0 && (
          <div style={{
            background: activeTab === 'bp'
              ? 'linear-gradient(135deg, #d85a4a 0%, #e87c6d 100%)'
              : 'linear-gradient(135deg, #e08b3a 0%, #f0a85a 100%)',
            borderRadius: 16,
            padding: '20px',
            color: '#fff',
            marginBottom: 16,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
            <div>
              <div style={{ fontSize: 13, opacity: 0.85 }}>
                {activeTab === 'bp' ? '最新血压' : '最新血糖'}
              </div>
              {activeTab === 'bp' ? (
                <div style={{ fontSize: 36, fontWeight: 700, marginTop: 4 }}>
                  {list[0].systolic}
                  <span style={{ fontSize: 16, fontWeight: 400, opacity: 0.8 }}>/{list[0].diastolic}</span>
                  <span style={{ fontSize: 12, fontWeight: 400, opacity: 0.7, marginLeft: 4 }}>mmHg</span>
                </div>
              ) : (
                <div style={{ fontSize: 36, fontWeight: 700, marginTop: 4 }}>
                  {list[0].value}
                  <span style={{ fontSize: 12, fontWeight: 400, opacity: 0.7, marginLeft: 4 }}>mmol/L</span>
                </div>
              )}
              <div style={{ fontSize: 12, opacity: 0.85, marginTop: 4 }}>
                {list[0].time}
                {activeTab === 'bs' && ` · ${list[0].type === 'fasting' ? '空腹' : '餐后'}`}
              </div>
            </div>
            <div>
              <span style={{
                display: 'inline-block',
                padding: '5px 12px',
                borderRadius: 20,
                fontSize: 12,
                fontWeight: 500,
                background: 'rgba(255,255,255,0.25)',
                color: '#fff',
              }}>
                {activeTab === 'bp'
                  ? bpStatus(list[0].systolic, list[0].diastolic).label
                  : bsStatus(list[0].value, list[0].type).label}
              </span>
            </div>
          </div>
        )}

        {/* 历史记录列表 */}
        <div className="card">
          <div className="card-title">
            <span>历史记录</span>
            <span className="more">{list.length}条</span>
          </div>

          {list.length === 0 ? (
            <div className="empty-state">
              <div className="empty-state-icon">{activeTab === 'bp' ? '❤️' : '🩸'}</div>
              <div className="empty-state-text">暂无记录，点击右下角按钮添加</div>
            </div>
          ) : (
            list.map((item, index) => {
              const st = activeTab === 'bp'
                ? bpStatus(item.systolic, item.diastolic)
                : bsStatus(item.value, item.type);
              return (
                <div key={item.id} style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '14px 0',
                  borderBottom: index < list.length - 1 ? '1px solid #f0ebe0' : 'none',
                }}>
                  <div style={{
                    width: 40, height: 40, borderRadius: 10,
                    background: st.color === 'danger' ? '#fef0ee' : st.color === 'warning' ? '#fef4e6' : '#eef5f2',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    {activeTab === 'bp'
                      ? <Icon.Heart color={st.color === 'danger' ? '#d85a4a' : st.color === 'warning' ? '#e08b3a' : '#3a8f7a'} size={18} />
                      : <Icon.Activity color={st.color === 'danger' ? '#d85a4a' : st.color === 'warning' ? '#e08b3a' : '#3a8f7a'} size={18} />
                    }
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 16, fontWeight: 600, color: '#2c3e3a' }}>
                      {activeTab === 'bp' ? (
                        <>
                          {item.systolic}<span style={{ fontSize: 12, color: '#8a9390', fontWeight: 400 }}>/{item.diastolic} mmHg</span>
                        </>
                      ) : (
                        <>
                          {item.value}<span style={{ fontSize: 12, color: '#8a9390', fontWeight: 400 }}> mmol/L</span>
                        </>
                      )}
                    </div>
                    <div style={{ fontSize: 12, color: '#a3a89f', marginTop: 3 }}>
                      {item.time}
                      {activeTab === 'bs' && ` · ${item.type === 'fasting' ? '空腹' : '餐后'}`}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className={`chip chip-${st.color}`}>{st.label}</span>
                    <button
                      className="btn btn-danger btn-sm"
                      style={{ padding: '4px 8px' }}
                      onClick={() => handleDelete(activeTab, item.id)}
                    >
                      <Icon.Trash size={13} />
                    </button>
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* 正常参考值 */}
        <div style={{
          background: '#eef5f2',
          borderRadius: 12,
          padding: '12px 16px',
          fontSize: 12,
          color: '#5a6e69',
          lineHeight: 1.6,
          marginBottom: 14,
        }}>
          <div style={{ fontWeight: 600, color: '#3a8f7a', marginBottom: 4 }}>📊 参考范围</div>
          {activeTab === 'bp' ? (
            <div>正常血压：收缩压 &lt; 130 mmHg，舒张压 &lt; 85 mmHg</div>
          ) : (
            <div>空腹血糖：3.9 ~ 6.1 mmol/L · 餐后2小时：&lt; 7.8 mmol/L</div>
          )}
        </div>
      </div>

      {/* 浮动添加按钮 */}
      <button className="fab" onClick={openAdd}>
        <Icon.Plus color="#fff" size={26} />
      </button>

      {/* 新增记录弹层 */}
      <BottomSheet
        visible={sheetVisible}
        title={`新增${activeTab === 'bp' ? '血压' : '血糖'}记录`}
        onClose={() => setSheetVisible(false)}
      >
        {activeTab === 'bp' ? (
          <div className="form-row">
            <div className="form-group">
              <label className="form-label">收缩压（高压）</label>
              <input
                className="form-input"
                type="number"
                placeholder="mmHg"
                value={form.systolic}
                onChange={e => setForm(prev => ({ ...prev, systolic: e.target.value }))}
              />
            </div>
            <div className="form-group">
              <label className="form-label">舒张压（低压）</label>
              <input
                className="form-input"
                type="number"
                placeholder="mmHg"
                value={form.diastolic}
                onChange={e => setForm(prev => ({ ...prev, diastolic: e.target.value }))}
              />
            </div>
          </div>
        ) : (
          <>
            <div className="form-group">
              <label className="form-label">血糖类型</label>
              <div style={{ display: 'flex', gap: 8 }}>
                <button
                  style={{
                    flex: 1,
                    padding: '10px 0',
                    borderRadius: 8,
                    fontSize: 13,
                    border: `1.5px solid ${form.type === 'fasting' ? '#3a8f7a' : '#ebe8e0'}`,
                    background: form.type === 'fasting' ? '#eef5f2' : '#fff',
                    color: form.type === 'fasting' ? '#3a8f7a' : '#5a6e69',
                    fontWeight: form.type === 'fasting' ? 500 : 400,
                  }}
                  onClick={() => setForm(prev => ({ ...prev, type: 'fasting' }))}
                >
                  空腹
                </button>
                <button
                  style={{
                    flex: 1,
                    padding: '10px 0',
                    borderRadius: 8,
                    fontSize: 13,
                    border: `1.5px solid ${form.type === 'postprandial' ? '#3a8f7a' : '#ebe8e0'}`,
                    background: form.type === 'postprandial' ? '#eef5f2' : '#fff',
                    color: form.type === 'postprandial' ? '#3a8f7a' : '#5a6e69',
                    fontWeight: form.type === 'postprandial' ? 500 : 400,
                  }}
                  onClick={() => setForm(prev => ({ ...prev, type: 'postprandial' }))}
                >
                  餐后
                </button>
              </div>
            </div>
            <div className="form-group">
              <label className="form-label">血糖值</label>
              <input
                className="form-input"
                type="number"
                step="0.1"
                placeholder="mmol/L"
                value={form.value}
                onChange={e => setForm(prev => ({ ...prev, value: e.target.value }))}
              />
            </div>
          </>
        )}

        <div className="form-hint" style={{ marginBottom: 16 }}>
          测量时间自动记录为当前时间
        </div>

        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
          {saving ? '保存中...' : '保存记录'}
        </button>
      </BottomSheet>
    </div>
  );
}
