import React, { useEffect, useRef, useState } from 'react';
import { Drawer } from 'antd';
import './style.less';
import Chat, { Message } from './Chat';
import { createFromIconfontCN } from '@ant-design/icons';
import AutoResizingTextarea from './AutoResizingTextarea/index';
import ReactMarkdown from 'react-markdown';
import { Line, Column, Pie } from '@ant-design/charts';

const IconFont = createFromIconfontCN({
  scriptUrl: '', // 请填写图标脚本地址
});

const AiChat: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState<string>('');
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  const [detailData, setDetailData] = useState<{ charts: any; content: string } | null>(null);

  const openDrawer = () => setVisible(true);
  const closeDrawer = () => setVisible(false);

  /**
   * 保持聊天容器滚动到底部
   */
  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  };

  /**
   * 发送消息的主函数
   */
  const handleSendMessage = async () => {
    if (isProcessing) return;

    const question = inputValue.trim();
    if (!question) return;

    const startTime = Date.now();
    let durationRecorded = false;
    let hasThinkTag = false;

    // 添加用户消息
    const userMsg: Message = { sender: 'user', content: question };
    setMessages((prev) => [...prev, userMsg]);
    setInputValue('');

    // 添加占位的机器人消息
    const botPlaceholder: Message = { sender: 'bot', content: '', loading: true };
    setMessages((prev) => [...prev, botPlaceholder]);

    setIsProcessing(true);

    try {
      const response = await fetch('http://116.62.47.88:5003/ask', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ question: question }),
      });


      if (!response.ok) {
        throw new Error(`服务器错误: ${response.status} ${response.statusText}`);
      }

      if (!response.body) {
        throw new Error('No response body');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let isThinking = false;

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        buffer += chunk;
        const parts = buffer.split('\n\n');

        for (let i = 0; i < parts.length - 1; i++) {
          const part = parts[i].trim();
          if (!part) continue;

          try {
            const parsed = JSON.parse(part);
            const {
              response: { chatText, charts, charts_done },
            } = parsed;

            if (part.indexOf('<think>') > -1) {
              isThinking = true;
              hasThinkTag = true;
            }
            if (part.indexOf('</think>') > -1) {
              isThinking = false;
              if (!durationRecorded) {
                const endTime = Date.now();
                const duration = Math.floor((endTime - startTime) / 1000);
                setMessages((prev) => {
                  const updated = [...prev];
                  const lastIndex = updated.length - 1;
                  if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
                    updated[lastIndex].duration = duration;
                    updated[lastIndex].loading = false;
                  }
                  return updated;
                });
                durationRecorded = true;
              }
            }

            const processedStr = chatText.replace(/<think>/g, '').replace(/<\/think>/g, '');

            setMessages((prev) => {
              const updated = [...prev];
              const lastIndex = updated.length - 1;
              if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
                if (isThinking) {
                  updated[lastIndex].thinkContent = (updated[lastIndex].thinkContent || '') + processedStr;
                } else {
                  updated[lastIndex].content += processedStr;
                }
              }
              return updated;
            });

            if (charts && Object.keys(charts).length > 0 && charts_done) {
              setMessages((prev) => {
                const updated = [...prev];
                const lastIndex = updated.length - 1;
                if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
                  updated[lastIndex].charts = charts;
                }
                return updated;
              });
            }
          } catch (e) {
            console.error('解析JSON失败:', e, '部分内容:', part);
          }
        }

        buffer = parts[parts.length - 1];
        scrollToBottom();
      }

      if (buffer.trim()) {
        try {
          const parsed = JSON.parse(buffer);
          const {
            response: { chatText, charts, charts_done },
          } = parsed;
          const processedStr = chatText.replace(/<think>/g, '').replace(/<\/think>/g, '');
          setMessages((prev) => {
            const updated = [...prev];
            const lastIndex = updated.length - 1;
            if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
              updated[lastIndex].content += processedStr;
            }
            return updated;
          });
          if (charts && Object.keys(charts).length > 0 && charts_done) {
            setMessages((prev) => {
              const updated = [...prev];
              const lastIndex = updated.length - 1;
              if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
                updated[lastIndex].charts = charts;
              }
              return updated;
            });
          }
        } catch (e) {
          console.error('解析剩余JSON失败:', e, buffer);
        }
      }

      setMessages((prev) => {
        const updated = [...prev];
        const lastIndex = updated.length - 1;
        if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
          updated[lastIndex].complete = true;
        }
        return updated;
      });
    } catch (error: any) {
      console.error('请求错误:', error);
      setMessages((prev) => {
        const updated = [...prev];
        const lastIndex = updated.length - 1;
        if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
          updated[lastIndex] = {
            sender: 'bot',
            content: `请求失败: ${error.message || '未知错误，请稍后重试'}`,
            loading: false,
          };
        }
        return updated;
      });
    } finally {
      if (!durationRecorded) {
        const endTime = Date.now();
        const duration = Math.floor((endTime - startTime) / 1000);
        setMessages((prev) => {
          const updated = [...prev];
          const lastIndex = updated.length - 1;
          if (lastIndex >= 0 && updated[lastIndex].sender === 'bot') {
            updated[lastIndex].duration = duration;
            updated[lastIndex].loading = false;
          }
          return updated;
        });
        durationRecorded = true;
      }
      setIsProcessing(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    if (!visible) {
      setMessages([]);
      setInputValue('');
      setDetailData(null);
    }
  }, [visible]);

  // 点击详情按钮时的回调，将图表数据和内容保存到 detailData 中
  const handleShowDetail = (charts: any, content: string) => {
    setDetailData({ charts, content });
  };

  // 辅助复制文本的函数
  const fallbackCopyTextToClipboard = (text: string) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = '0';
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    document.body.appendChild(textArea);
    textArea.select();
    
    try {
      const successful = document.execCommand('copy');
      if (successful) console.log('复制成功');
    } catch (err) {
      console.error('复制失败', err);
    }
    document.body.removeChild(textArea);
  };

  const handleCopy = (text: string) => {
    if (!text) {
      console.error('未获取到文本内容');
      return;
    }
    if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          console.log('复制成功');
        })
        .catch((err) => {
          console.error('使用 Clipboard API 复制失败，尝试备用方案：', err);
          fallbackCopyTextToClipboard(text);
        });
    } else {
      fallbackCopyTextToClipboard(text);
    }
  };

  return (
    <>
      {/* 悬浮按钮 */}
      <div className="ai-chat-drawer-button" onClick={openDrawer}>
        <img src={require('./images/ai.png')} alt="" />
      </div>

      {/* 抽屉组件 */}
      <Drawer
        className={detailData ? 'ai-chat-drawer hasDetail' : 'ai-chat-drawer'}
        headerStyle={{ display: 'none' }}
        bodyStyle={{ background: 'rgba(240,246,252,0.98)', padding: 8 }}
        placement="right"
        onClose={closeDrawer}
        open={visible}
        destroyOnClose
        width={detailData ? '94%' : 560}
        mask={false}
      >
        <div className="chat-header">
          <div className="chat-header-title">
            <img src={require('./images/ai-eyes.png')} alt="" />
            <span>智能小K</span>
          </div>
          <div className="closeBtn" onClick={closeDrawer}>
            <IconFont style={{ fontSize: 16 }} type={'iconquxiao'} />
          </div>
        </div>
        <div className="chat-content-wrap">
          <div className="chat-content">
            {messages.length === 0 && <img src={require('./images/ai_descr.png')} alt="" />}
            {messages.length > 0 && <Chat messages={messages} chatContainerRef={chatContainerRef} setMessages={setMessages} onShowDetail={handleShowDetail} />}
            <div className={messages.length > 0 ? 'startInput large' : 'startInput'}>
              <AutoResizingTextarea value={inputValue} onChange={(e) => setInputValue(e.target.value)} onKeyPress={handleKeyPress} placeholder="请输入您的问题..." />
              <div className={`chat-sendBtn ${isProcessing ? 'isProcessing' : ''} ${inputValue.length > 0 ? 'hasText' : ''}`} onClick={handleSendMessage}>
                <img src={require('./images/send_white.png')} alt="" />
              </div>
            </div>
          </div>
          {/* 详情展示区域 */}
          {detailData && (
            <div className="chat-detail">
              <div className="detail-view">
                <div className="detail-header">
                  <span className="goback" onClick={() => setDetailData(null)}>
                    <IconFont type={'iconxiangzuo'} style={{ fontSize: 16 }} />
                    返回
                  </span>
                  <span className="favorite">
                    <IconFont type={'iconshoucang'} style={{ fontSize: 16 }} /> 收藏
                  </span>
                </div>
                <div className="detail-body">
                  <div className="charts">
                    {detailData.charts &&
                      detailData.charts.data &&
                      detailData.charts.data.length > 0 &&
                      (detailData.charts.type === 'LineChart' ? (
                        <Line {...detailData.charts} />
                      ) : detailData.charts.type === 'ColumnChart' ? (
                        <Column {...detailData.charts} />
                      ) : detailData.charts.type === 'PieChart' ? (
                        <Pie {...detailData.charts} />
                      ) : null)}
                  </div>

                  <div style={{ height: 16 }}></div>
                  <ReactMarkdown skipHtml={false}>{detailData.content}</ReactMarkdown>
                </div>
              </div>
            </div>
          )}
        </div>
      </Drawer>
    </>
  );
};

export default AiChat;
