// AI助手对话页 - 全栈版本
function AIPage({ navigate, goBack }) {
  const { state, dispatch, showToast } = React.useContext(AppContext);
  const [input, setInput] = React.useState('');
  const [isTyping, setIsTyping] = React.useState(false);
  const [loaded, setLoaded] = React.useState(false);
  const messagesEndRef = React.useRef(null);

  const messages = state.aiMessages;

  const DISCLAIMER = '提示：本内容仅供自我管理参考，不能替代医生诊断与处方，请遵从线下医师意见。';

  const quickQuestions = [
    '我有哪些慢病？',
    '今天该吃什么药？',
    '高血压日常注意事项',
    '血糖偏高怎么办',
  ];

  // 加载历史消息
  React.useEffect(() => {
    loadMessages();
  }, []);

  async function loadMessages() {
    try {
      const data = await api.getAIMessages();
      dispatch({ type: 'SET_AI_MESSAGES', payload: data });
    } catch (e) {
      // 加载失败忽略
    } finally {
      setLoaded(true);
    }
  }

  React.useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, isTyping]);

  const sendMessage = async (text) => {
    if (!text.trim() || isTyping) return;

    const userMsg = {
      id: Date.now(),
      role: 'user',
      content: text.trim(),
    };
    dispatch({ type: 'SET_AI_MESSAGES', payload: [...messages, userMsg] });
    setInput('');
    setIsTyping(true);

    try {
      const res = await api.sendAIMessage(text.trim());
      dispatch({
        type: 'SET_AI_MESSAGES',
        payload: [...messages, userMsg, {
          id: Date.now() + 1,
          role: 'assistant',
          content: res.reply,
        }]
      });
    } catch (err) {
      showToast(err.message);
    } finally {
      setIsTyping(false);
    }
  };

  const handleSend = () => sendMessage(input);
  const handleQuickQuestion = (q) => sendMessage(q);

  // 展示欢迎消息（数据库中无消息时）
  const showWelcome = loaded && messages.length === 0;

  return (
    <div className="page page-enter" style={{
      display: 'flex',
      flexDirection: 'column',
      paddingBottom: 0,
      background: '#faf8f3',
    }}>
      <TopBar title="AI健康助手" onBack={goBack} />

      {/* 快捷问题（仅欢迎时显示） */}
      {showWelcome && (
        <div style={{ padding: '0 16px 12px' }}>
          <div style={{ fontSize: 12, color: '#8a9390', marginBottom: 8 }}>试试这些问题：</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {quickQuestions.map(q => (
              <button
                key={q}
                style={{
                  textAlign: 'left',
                  padding: '10px 14px',
                  background: '#fff',
                  borderRadius: 10,
                  fontSize: 13,
                  color: '#3a8f7a',
                  border: '1px solid #eef5f2',
                  boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
                }}
                onClick={() => handleQuickQuestion(q)}
              >
                {q}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 消息列表 */}
      <div style={{
        flex: 1,
        overflowY: 'auto',
        padding: '12px 16px',
        display: 'flex',
        flexDirection: 'column',
        gap: 14,
      }}>
        {showWelcome && (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>
            <div style={{
              width: 34, height: 34, borderRadius: '50%',
              background: 'linear-gradient(135deg, #7c5cd8, #9b85e8)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Icon.Bot color="#fff" size={18} />
            </div>
            <div style={{
              maxWidth: '75%',
              background: '#fff',
              color: '#2c3e3a',
              padding: '10px 14px',
              borderRadius: '14px 14px 14px 4px',
              fontSize: 14,
              lineHeight: 1.6,
              boxShadow: '0 1px 6px rgba(0,0,0,0.05)',
            }}>
              您好！我是您的慢病管理AI助手。我可以帮您查询档案信息、了解慢病管理知识、提供日常照护建议。
              <br /><br />
              请问有什么可以帮您的？
              <div style={{
                marginTop: 10,
                paddingTop: 8,
                borderTop: '1px dashed #ebe8e0',
                fontSize: 11,
                color: '#a3a89f',
                lineHeight: 1.5,
              }}>
                {DISCLAIMER}
              </div>
            </div>
          </div>
        )}

        {messages.map(msg => (
          <div
            key={msg.id}
            style={{
              display: 'flex',
              justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
              alignItems: 'flex-end',
              gap: 8,
            }}
          >
            {msg.role === 'assistant' && (
              <div style={{
                width: 34, height: 34, borderRadius: '50%',
                background: 'linear-gradient(135deg, #7c5cd8, #9b85e8)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                <Icon.Bot color="#fff" size={18} />
              </div>
            )}
            <div style={{
              maxWidth: '75%',
              background: msg.role === 'user' ? '#3a8f7a' : '#fff',
              color: msg.role === 'user' ? '#fff' : '#2c3e3a',
              padding: '10px 14px',
              borderRadius: msg.role === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
              fontSize: 14,
              lineHeight: 1.6,
              boxShadow: msg.role === 'user' ? 'none' : '0 1px 6px rgba(0,0,0,0.05)',
              whiteSpace: 'pre-wrap',
              wordBreak: 'break-word',
            }}>
              {msg.content}
              {msg.role === 'assistant' && (
                <div style={{
                  marginTop: 10,
                  paddingTop: 8,
                  borderTop: '1px dashed #ebe8e0',
                  fontSize: 11,
                  color: '#a3a89f',
                  lineHeight: 1.5,
                }}>
                  {DISCLAIMER}
                </div>
              )}
            </div>
            {msg.role === 'user' && (
              <div style={{
                width: 34, height: 34, borderRadius: '50%',
                background: '#e08b3a',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff',
                fontWeight: 600,
                fontSize: 14,
                flexShrink: 0,
              }}>
                我
              </div>
            )}
          </div>
        ))}

        {isTyping && (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>
            <div style={{
              width: 34, height: 34, borderRadius: '50%',
              background: 'linear-gradient(135deg, #7c5cd8, #9b85e8)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Icon.Bot color="#fff" size={18} />
            </div>
            <div style={{
              background: '#fff',
              padding: '12px 16px',
              borderRadius: '14px 14px 14px 4px',
              display: 'flex',
              gap: 4,
            }}>
              {[0, 1, 2].map(i => (
                <div key={i} style={{
                  width: 6, height: 6, borderRadius: '50%',
                  background: '#b5b9b2',
                  animation: `typingBounce 1.4s infinite ease-in-out ${i * 0.16}s`,
                }} />
              ))}
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* 输入栏 */}
      <div style={{
        padding: '10px 12px',
        paddingBottom: `calc(10px + env(safe-area-inset-bottom))`,
        background: '#fff',
        borderTop: '1px solid #ebe8e0',
        display: 'flex',
        alignItems: 'center',
        gap: 10,
      }}>
        <input
          style={{
            flex: 1,
            padding: '10px 14px',
            border: '1.5px solid #ebe8e0',
            borderRadius: 20,
            fontSize: 14,
            outline: 'none',
            background: '#faf8f3',
          }}
          type="text"
          placeholder="输入您的问题..."
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && handleSend()}
        />
        <button
          style={{
            width: 40, height: 40,
            borderRadius: '50%',
            background: input.trim() ? '#3a8f7a' : '#d0cdc4',
            color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background 0.2s',
          }}
          onClick={handleSend}
          disabled={!input.trim() || isTyping}
        >
          <Icon.Send color="#fff" size={18} />
        </button>
      </div>

      <style>{`
        @keyframes typingBounce {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
          30% { transform: translateY(-5px); opacity: 1; }
        }
      `}</style>
    </div>
  );
}
