// 我的页面 - 全栈版本
function ProfilePage({ navigate, goBack, onLogout }) {
  const { state, dispatch, showToast } = React.useContext(AppContext);
  const { user, diseases, medications } = state;

  const [editSheetVisible, setEditSheetVisible] = React.useState(false);
  const [editForm, setEditForm] = React.useState({ ...user });
  const [saving, setSaving] = React.useState(false);

  const openEdit = () => {
    setEditForm({ ...user });
    setEditSheetVisible(true);
  };

  const handleSaveProfile = async () => {
    if (!editForm.name.trim()) {
      showToast('请输入姓名');
      return;
    }
    setSaving(true);
    try {
      const updated = await api.updateProfile(editForm);
      dispatch({ type: 'SET_USER', payload: updated });
      showToast('已保存');
      setEditSheetVisible(false);
    } catch (err) {
      showToast(err.message);
    } finally {
      setSaving(false);
    }
  };

  const cciScore = calculateCCIScore(diseases);

  const menuItems = [
    {
      icon: <Icon.File color="#3a8f7a" size={20} />,
      title: '健康档案报告',
      subtitle: '导出完整慢病档案',
      onClick: () => navigate('report'),
    },
    {
      icon: <Icon.Activity color="#e08b3a" size={20} />,
      title: 'CCI共病指数',
      subtitle: `当前得分：${cciScore} 分`,
      onClick: () => navigate('cci'),
    },
    {
      icon: <Icon.Pill color="#4a7dac" size={20} />,
      title: '用药管理',
      subtitle: `${medications.length}种在用药物`,
      onClick: () => navigate('medication'),
    },
    {
      icon: <Icon.Settings color="#8a9390" size={20} />,
      title: '设置',
      subtitle: '提醒、隐私、数据管理',
      onClick: () => showToast('设置功能开发中'),
    },
    {
      icon: <Icon.Info color="#8a9390" size={20} />,
      title: '关于本工具',
      subtitle: '版本 1.0.0（全栈版）',
      onClick: () => showToast('慢病共病健康管理工具 v1.0.0'),
    },
  ];

  return (
    <div className="page page-enter">
      {/* 头部用户信息 */}
      <div style={{
        background: 'linear-gradient(135deg, #3a8f7a 0%, #5aab94 100%)',
        padding: '30px 20px 70px',
        color: '#fff',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute',
          width: 180, height: 180,
          borderRadius: '50%',
          background: 'rgba(255,255,255,0.08)',
          top: -50, right: -40,
        }} />
        <div style={{
          position: 'absolute',
          width: 100, height: 100,
          borderRadius: '50%',
          background: 'rgba(255,255,255,0.06)',
          bottom: -20, left: -10,
        }} />
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: 14,
          position: 'relative',
          zIndex: 1,
        }}>
          <Avatar name={user.name || user.nickname} size={64} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 20, fontWeight: 700 }}>
              {user.name || user.nickname || '未设置'}
            </div>
            <div style={{ fontSize: 13, opacity: 0.85, marginTop: 4 }}>
              {user.age ? user.age + '岁' : '年龄未设置'} · {user.gender || '男'} · {user.phone}
            </div>
            <div style={{ fontSize: 12, opacity: 0.75, marginTop: 2 }}>
              {user.height ? `身高 ${user.height}cm` : ''}
              {user.weight ? ` · 体重 ${user.weight}kg` : ''}
              {!user.height && !user.weight ? '身高体重未设置' : ''}
            </div>
          </div>
          <button
            style={{
              padding: '6px 12px',
              borderRadius: 20,
              fontSize: 12,
              background: 'rgba(255,255,255,0.2)',
              color: '#fff',
              border: '1px solid rgba(255,255,255,0.3)',
            }}
            onClick={openEdit}
          >
            编辑资料
          </button>
        </div>
      </div>

      {/* 主体内容 */}
      <div style={{ padding: '0 16px', marginTop: -50, position: 'relative', zIndex: 2 }}>
        {/* 统计卡片 */}
        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-around', textAlign: 'center' }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#d85a4a' }}>{diseases.length}</div>
              <div style={{ fontSize: 12, color: '#8a9390', marginTop: 2 }}>慢病</div>
            </div>
            <div style={{ width: 1, background: '#ebe8e0' }} />
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#4a7dac' }}>{medications.length}</div>
              <div style={{ fontSize: 12, color: '#8a9390', marginTop: 2 }}>用药</div>
            </div>
            <div style={{ width: 1, background: '#ebe8e0' }} />
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#e08b3a' }}>{cciScore}</div>
              <div style={{ fontSize: 12, color: '#8a9390', marginTop: 2 }}>CCI分</div>
            </div>
          </div>
        </div>

        {/* 功能菜单 */}
        <div className="card" style={{ padding: '0 18px' }}>
          {menuItems.map((item, i) => (
            <div
              key={item.title}
              onClick={item.onClick}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 12,
                padding: '15px 0',
                borderBottom: i < menuItems.length - 1 ? '1px solid #f0ebe0' : 'none',
                cursor: 'pointer',
              }}
            >
              <div style={{
                width: 38, height: 38,
                borderRadius: 10,
                background: '#faf8f3',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {item.icon}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: '#2c3e3a' }}>
                  {item.title}
                </div>
                {item.subtitle && (
                  <div style={{ fontSize: 12, color: '#a3a89f', marginTop: 2 }}>
                    {item.subtitle}
                  </div>
                )}
              </div>
              <Icon.Chevron color="#c8c5bd" />
            </div>
          ))}
        </div>

        {/* 免责声明 */}
        <div style={{
          background: '#f0ebe0',
          borderRadius: 12,
          padding: '14px 16px',
          fontSize: 11,
          color: '#8a7e64',
          lineHeight: 1.7,
          marginBottom: 16,
          textAlign: 'center',
        }}>
          <p>本工具仅供个人慢病档案管理参考</p>
          <p>不提供医疗诊断与处方服务</p>
          <p>具体诊疗请遵从线下医师意见</p>
        </div>

        {/* 退出登录 */}
        <button
          className="btn btn-secondary"
          style={{ marginBottom: 24 }}
          onClick={() => {
            if (confirm('确定要退出登录吗？')) {
              onLogout();
            }
          }}
        >
          退出登录
        </button>
      </div>

      {/* 编辑资料弹层 */}
      <BottomSheet
        visible={editSheetVisible}
        title="编辑个人资料"
        onClose={() => setEditSheetVisible(false)}
      >
        <div className="form-group">
          <label className="form-label">姓名</label>
          <input
            className="form-input"
            type="text"
            value={editForm.name}
            onChange={e => setEditForm(prev => ({ ...prev, name: e.target.value }))}
          />
        </div>

        <div className="form-group">
          <label className="form-label">昵称</label>
          <input
            className="form-input"
            type="text"
            value={editForm.nickname}
            onChange={e => setEditForm(prev => ({ ...prev, nickname: e.target.value }))}
          />
        </div>

        <div className="form-row">
          <div className="form-group">
            <label className="form-label">年龄</label>
            <input
              className="form-input"
              type="number"
              value={editForm.age || ''}
              onChange={e => setEditForm(prev => ({ ...prev, age: Number(e.target.value) || 0 }))}
            />
          </div>
          <div className="form-group">
            <label className="form-label">性别</label>
            <div style={{ display: 'flex', gap: 8 }}>
              <button
                style={{
                  flex: 1,
                  padding: '12px 0',
                  borderRadius: 10,
                  fontSize: 14,
                  border: `1.5px solid ${editForm.gender === '男' ? '#3a8f7a' : '#ebe8e0'}`,
                  background: editForm.gender === '男' ? '#eef5f2' : '#fff',
                  color: editForm.gender === '男' ? '#3a8f7a' : '#5a6e69',
                  fontWeight: editForm.gender === '男' ? 500 : 400,
                }}
                onClick={() => setEditForm(prev => ({ ...prev, gender: '男' }))}
              >
                男
              </button>
              <button
                style={{
                  flex: 1,
                  padding: '12px 0',
                  borderRadius: 10,
                  fontSize: 14,
                  border: `1.5px solid ${editForm.gender === '女' ? '#3a8f7a' : '#ebe8e0'}`,
                  background: editForm.gender === '女' ? '#eef5f2' : '#fff',
                  color: editForm.gender === '女' ? '#3a8f7a' : '#5a6e69',
                  fontWeight: editForm.gender === '女' ? 500 : 400,
                }}
                onClick={() => setEditForm(prev => ({ ...prev, gender: '女' }))}
              >
                女
              </button>
            </div>
          </div>
        </div>

        <div className="form-row">
          <div className="form-group">
            <label className="form-label">身高(cm)</label>
            <input
              className="form-input"
              type="number"
              value={editForm.height || ''}
              onChange={e => setEditForm(prev => ({ ...prev, height: Number(e.target.value) || 0 }))}
            />
          </div>
          <div className="form-group">
            <label className="form-label">体重(kg)</label>
            <input
              className="form-input"
              type="number"
              value={editForm.weight || ''}
              onChange={e => setEditForm(prev => ({ ...prev, weight: Number(e.target.value) || 0 }))}
            />
          </div>
        </div>

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