import React, { useState, useRef } from 'react';
import { t } from '@/i18n';
import { chat } from '../../services/ai';
// Taro mini-program - AI Chat Assistant

/**
 * P1. AI Chat - Full-screen AI chat interface
 *
 * Suggestion chips, message list, fixed input bar
 */

interface ChatMessage {
  isAi: boolean;
  text: string;
}

const AiChatPage: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([
    { isAi: true, text: t('ai_chat_greeting') },
  ]);
  const [inputText, setInputText] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [scrollToId, setScrollToId] = useState('msg-0');

  const suggestions = [
    t('ai_chat_suggest1'),
    t('ai_chat_suggest2'),
    t('ai_chat_suggest3'),
    t('ai_chat_suggest4'),
  ];

  const addMessages = (userText: string) => {
    const userMsg: ChatMessage = { isAi: false, text: userText };
    setMessages((prev) => {
      const next = [...prev, userMsg];
      const userIdx = next.length - 1;
      setScrollToId(`msg-${userIdx}`);
      return next;
    });
    setInputText('');
    setIsTyping(true);

    chat(userText)
      .then((response) => {
        const aiText = response.message || t('ai_chat_greeting');
        setMessages((prev) => {
          const next = [...prev, { isAi: true, text: aiText }];
          const aiIdx = next.length - 1;
          setScrollToId(`msg-${aiIdx}`);
          return next;
        });
      })
      .catch(() => {
        setMessages((prev) => {
          const next = [...prev, { isAi: true, text: t('ai_chat_error') || '抱歉，请稍后再试。' }];
          const aiIdx = next.length - 1;
          setScrollToId(`msg-${aiIdx}`);
          return next;
        });
      })
      .finally(() => setIsTyping(false));
  };

  const handleSend = () => {
    const text = inputText.trim();
    if (!text || isTyping) return;
    addMessages(text);
  };

  const handleChipTap = (chip: string) => {
    if (isTyping) return;
    addMessages(chip);
  };

  return (
    <view className="chat-page">
      {/* Header */}
      <view className="chat-header">
        <text className="chat-header-title">{t('ai_chat_title')}</text>
      </view>

      {/* Message List */}
      <scroll-view
        scrollY
        className="chat-messages"
        scrollIntoView={scrollToId}
        scrollWithAnimation
      >
        {messages.map((msg, i) => (
          <view
            key={i}
            id={`msg-${i}`}
            className={`msg-row ${msg.isAi ? 'msg-ai' : 'msg-user'}`}
          >
            {msg.isAi && (
              <view className="ai-avatar">
                <text className="ai-avatar-icon">&#10024;</text>
              </view>
            )}
            <view
              className={`msg-bubble ${msg.isAi ? 'bubble-ai' : 'bubble-user'}`}
            >
              <text className={`msg-text ${msg.isAi ? 'text-ai' : 'text-user'}`}>
                {msg.text}
              </text>
            </view>
          </view>
        ))}

        {/* Typing indicator */}
        {isTyping && (
          <view className="msg-row msg-ai">
            <view className="ai-avatar">
              <text className="ai-avatar-icon">&#10024;</text>
            </view>
            <view className="msg-bubble bubble-ai">
              <text className="msg-text text-ai">...</text>
            </view>
          </view>
        )}

        {/* Suggestion Chips */}
        {messages.length <= 2 && (
          <view className="chips-container">
            <scroll-view scrollX className="chips-scroll">
              {suggestions.map((chip, i) => (
                <view
                  key={i}
                  className="chip"
                  onClick={() => handleChipTap(chip)}
                >
                  <text className="chip-text">{chip}</text>
                </view>
              ))}
            </scroll-view>
          </view>
        )}

        {/* Bottom spacer for scroll */}
        <view className="msg-spacer" />
      </scroll-view>

      {/* Input Bar */}
      <view className="input-bar">
        <view className="input-wrap">
          <input
            className="chat-input"
            placeholder={t('ai_chat_input_hint')}
            value={inputText}
            onInput={(e: any) => setInputText(e.detail.value)}
            onConfirm={handleSend}
            confirmType="send"
          />
        </view>
        <view className="send-btn" onClick={handleSend}>
          <text className="send-icon">&#8593;</text>
        </view>
      </view>
    </view>
  );
};

export default AiChatPage;

/*
CSS (index.scss):

.chat-page {
  display: flex; flex-direction: column;
  height: 100vh; background: #F8F9FC;
}

.chat-header {
  display: flex; align-items: center; justify-content: center;
  height: 88rpx; background: white;
  border-bottom: 1rpx solid #F1F3F8;
  padding-top: env(safe-area-inset-top);
}
.chat-header-title { font-size: 32rpx; font-weight: 600; color: #141723; }

.chat-messages {
  flex: 1; padding: 24rpx 32rpx; overflow-y: auto;
}

.msg-row { display: flex; margin-bottom: 24rpx; }
.msg-ai { justify-content: flex-start; }
.msg-user { justify-content: flex-end; }

.ai-avatar {
  width: 64rpx; height: 64rpx; border-radius: 16rpx;
  background: linear-gradient(135deg, #6C5CE7, #9B8FFF);
  display: flex; align-items: center; justify-content: center;
  margin-right: 16rpx; flex-shrink: 0;
}
.ai-avatar-icon { font-size: 28rpx; }

.msg-bubble { max-width: 75%; border-radius: 20rpx; padding: 20rpx 24rpx; }
.bubble-ai { background: #F1F3F8; border-top-left-radius: 4rpx; }
.bubble-user { background: #6C5CE7; border-top-right-radius: 4rpx; }

.msg-text { font-size: 28rpx; line-height: 1.6; white-space: pre-wrap; }
.text-ai { color: #141723; }
.text-user { color: white; }

.chips-container { padding: 8rpx 0 16rpx; }
.chips-scroll { white-space: nowrap; }
.chip {
  display: inline-block; margin-right: 16rpx;
  padding: 14rpx 24rpx; background: #F3F1FF;
  border: 1rpx solid rgba(108,92,231,0.2);
  border-radius: 999rpx;
}
.chip-text { font-size: 24rpx; color: #6C5CE7; white-space: nowrap; }

.msg-spacer { height: 32rpx; }

.input-bar {
  display: flex; align-items: center;
  padding: 16rpx 24rpx; padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
  background: white; border-top: 1rpx solid #F1F3F8;
}
.input-wrap {
  flex: 1; height: 72rpx; background: #F1F3F8; border-radius: 999rpx;
  display: flex; align-items: center; padding: 0 24rpx;
}
.chat-input { flex: 1; font-size: 28rpx; color: #141723; background: transparent; }
.send-btn {
  width: 72rpx; height: 72rpx; margin-left: 16rpx;
  background: #6C5CE7; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
}
.send-icon { color: white; font-size: 36rpx; font-weight: 700; }
*/
