'use client';

import { useState, useCallback, useEffect } from 'react';
import { useGenSupContentV2 } from './useIm';
import { useAtomValue, useSetAtom } from 'jotai';
import { msgListAtom, selectedConversationIdAtom, ExtendedMessage, isCoinInsufficientAtom } from '@/atoms/im';
import { useNimChat } from '@/context/NimChat/useNimChat';
import { ApiError } from '@/types/api';
import { COIN_INSUFFICIENT_ERROR_CODE } from './useWallet';

export interface ReplySuggestion {
  id: string;
  text: string;
  isSkeleton?: boolean; // 标识是否为骨架屏
}

interface UseAiReplySuggestionsProps {
  aiId?: number;
}

export const useAiReplySuggestions = ({ 
  aiId
}: UseAiReplySuggestionsProps = {}) => {
  const [allSuggestions, setAllSuggestions] = useState<ReplySuggestion[]>([]); // 保存所有建议数据
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(3); // 固定3页，每页3条数据
  const [isLoading, setIsLoading] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  const [lastAiMessageId, setLastAiMessageId] = useState<string>(''); // 记录最后一条AI消息的ID
  const [loadedPages, setLoadedPages] = useState<Set<number>>(new Set([1])); // 记录已加载的页面，默认第1页已加载
  const [batchNo, setBatchNo] = useState<string>(''); // 保存批次号
  const [excContentList, setExcContentList] = useState<string[]>([]); // 保存排除内容列表
  const [isPageLoading, setIsPageLoading] = useState(false); // 页面级别的加载状态
  const [isRequesting, setIsRequesting] = useState(false); // 防止重复请求的标志
  const setIsCoinInsufficient = useSetAtom(isCoinInsufficientAtom);

  // 每页显示的建议数量
  const pageSize = 3;

  // 根据当前页码获取当前页的建议
  const suggestions = allSuggestions.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  
  // 检查当前页面是否已加载数据
  const isCurrentPageLoaded = loadedPages.has(currentPage);
  
  // 如果当前页面未加载完成，返回骨架屏数据
  const displaySuggestions = isCurrentPageLoaded ? suggestions : Array.from({ length: pageSize }, (_, index) => ({
    id: `skeleton-${currentPage}-${index}`,
    text: '', // 空文本表示骨架屏
    isSkeleton: true
  }));

  const { mutateAsync: genSupContentV2, isPending: isGenSupContentV2Pending } = useGenSupContentV2();
  const { nim } = useNimChat();
  const msgList = useAtomValue(msgListAtom);
  const selectedConversationId = useAtomValue(selectedConversationIdAtom);

  // 获取当前会话的消息列表
  const currentMessages = selectedConversationId ? (msgList.get(selectedConversationId) || []) : [];

  // 获取最后一条非loading消息
  const getLastMessage = useCallback((): ExtendedMessage | null => {
    const normalMessages = currentMessages.filter(msg => !msg.isLoadingMessage);
    return normalMessages.length > 0 ? normalMessages[normalMessages.length - 1] : null;
  }, [currentMessages]);

  // 判断消息是否来自AI（非用户发送）
  const isMessageFromAI = useCallback((message: ExtendedMessage): boolean => {
    if (!nim || !selectedConversationId) return false;
    const targetId = nim.V2NIMConversationIdUtil.parseConversationTargetId(selectedConversationId);
    return targetId === message.senderId;
  }, [nim, selectedConversationId]);

  // 检查是否需要获取新的建议
  const shouldFetchNewSuggestions = useCallback((): boolean => {
    const lastMessage = getLastMessage();
    if (!lastMessage) return false;
    
    const isFromAI = isMessageFromAI(lastMessage);
    const isNewAIMessage = isFromAI && lastMessage.messageServerId !== lastAiMessageId;
    
    return isFromAI && isNewAIMessage;
  }, [getLastMessage, isMessageFromAI, lastAiMessageId]);

  // 获取AI建议 - 先获取第一批数据展示，然后静默获取剩余数据
  const fetchSuggestions = useCallback(async () => {
    if (!aiId) return;
    
    // 防止重复调用 - 如果正在加载中或正在请求中则直接返回
    if (isLoading || isGenSupContentV2Pending || isRequesting) {
      console.log('🚫 正在加载中或请求中，跳过重复请求');
      return;
    }
    
    setIsRequesting(true);
    
    setIsLoading(true);
    try {
      console.log('🤖 开始获取AI建议，aiId:', aiId);
      const batchNum = new Date().getTime();
      
      // 第一次调用API，获取3条数据并立即展示
      console.log('🤖 第1次调用API，batchNo:', batchNo, 'excContentList: []');
      const firstResponse = await genSupContentV2({ 
        aiId, 
        excContentList: [] 
      });
      
      console.log('🤖 第1次API返回结果:', firstResponse);
      
      if (firstResponse && firstResponse.contentList && Array.isArray(firstResponse.contentList)) {
        // 将第一批数据转换为建议对象
        const firstBatchSuggestions = firstResponse.contentList.map((text, index) => ({
          id: `${batchNum}-0-${index}`,
          text
        }));
        
        // 立即保存第一批数据并展示
        setAllSuggestions(firstBatchSuggestions);
        setTotalPages(3); // 固定3页
        // 不强制跳转到第一页，保持用户当前页面位置
        setBatchNo(firstResponse.batchNo);
        setExcContentList([...firstResponse.contentList]);
        
        // 记录最后一条AI消息的ID
        const lastMessage = getLastMessage();
        if (lastMessage && isMessageFromAI(lastMessage)) {
          setLastAiMessageId(lastMessage.messageServerId);
        }
        
        // 静默获取剩余数据
        fetchRemainingSuggestions(firstResponse.batchNo, firstResponse.contentList, firstBatchSuggestions);
      } else {
        setAllSuggestions([]);
        setTotalPages(1);
        setCurrentPage(1);
      }
    } catch (error) {
      if (error instanceof ApiError) {
        if (error.errorCode === COIN_INSUFFICIENT_ERROR_CODE) {
          setIsCoinInsufficient(true);
          setAllSuggestions([]);
          setTotalPages(1);
          setCurrentPage(1);
          setIsVisible(false);
          return;
        }
      }
      console.error('❌ Failed to fetch AI suggestions:', error);
      setAllSuggestions([]);
      setTotalPages(1);
      setCurrentPage(1);
    } finally {
      setIsLoading(false);
      setIsRequesting(false);
    }
  }, [aiId, genSupContentV2, getLastMessage, isMessageFromAI, isLoading, isGenSupContentV2Pending, isRequesting]);

  // 静默获取剩余的建议数据
  const fetchRemainingSuggestions = useCallback(async (batchNo: string, currentExcContentList: string[], currentSuggestions: ReplySuggestion[]) => {
    if (!aiId) return;
    
    try {
      let allSuggestions = [...currentSuggestions];
      let excContentList = [...currentExcContentList];
      
      // 获取第2批数据
      console.log('🤖 静默获取第2批数据，batchNo:', batchNo, 'excContentList:', excContentList);
      const secondResponse = await genSupContentV2({ 
        aiId, 
        batchNo, 
        excContentList 
      });
      
      if (secondResponse && secondResponse.contentList && Array.isArray(secondResponse.contentList)) {
        const secondBatchSuggestions = secondResponse.contentList.map((text, index) => ({
          id: `${batchNo}-1-${index}`,
          text
        }));
        
        allSuggestions.push(...secondBatchSuggestions);
        excContentList.push(...secondResponse.contentList);
        
        // 更新数据
        setAllSuggestions(allSuggestions);
        setExcContentList(excContentList);
        
        // 标记第2页已加载
        setLoadedPages(prev => new Set([...prev, 2]));
      }
      
      // 获取第3批数据
      console.log('🤖 静默获取第3批数据，batchNo:', batchNo, 'excContentList:', excContentList);
      const thirdResponse = await genSupContentV2({ 
        aiId, 
        batchNo, 
        excContentList 
      });
      
      if (thirdResponse && thirdResponse.contentList && Array.isArray(thirdResponse.contentList)) {
        const thirdBatchSuggestions = thirdResponse.contentList.map((text, index) => ({
          id: `${batchNo}-2-${index}`,
          text
        }));
        
        allSuggestions.push(...thirdBatchSuggestions);
        
        // 更新最终数据
        setAllSuggestions(allSuggestions);
        
        // 标记第3页已加载
        setLoadedPages(prev => new Set([...prev, 3]));
      }
    } catch (error) {
      console.error('❌ 静默获取剩余数据失败:', error);
    }
  }, [aiId, genSupContentV2]);

  // 切换页面 - 检查数据是否已加载，未加载则显示骨架屏
  const handlePageChange = useCallback((page: number) => {
    if (page >= 1 && page <= totalPages && page !== currentPage) {
      console.log('📄 切换到第', page, '页');
      
      // 检查目标页面是否已加载数据
      const isTargetPageLoaded = loadedPages.has(page);
      
      if (isTargetPageLoaded) {
        console.log('✅ 第', page, '页数据已加载，直接切换');
        setCurrentPage(page);
        setIsPageLoading(false); // 清除页面加载状态
      } else {
        console.log('⏳ 第', page, '页数据未加载，显示骨架屏');
        setIsPageLoading(true);
        setCurrentPage(page);
        
        // 如果数据正在后台加载，等待数据加载完成
        // 这里不需要额外处理，因为数据加载完成后会自动更新UI
      }
    }
  }, [currentPage, totalPages, loadedPages]);



  // 显示建议面板
  const showSuggestions = useCallback(() => {
    setIsVisible(true);
    
    // 检查是否需要获取新的建议
    if (shouldFetchNewSuggestions()) {
      console.log('🔄 检测到新的AI消息，获取新建议');
      // 不重置页面，保持用户当前的页面位置
      fetchSuggestions();
    } else if (allSuggestions.length === 0) {
      console.log('📝 没有建议数据，获取建议');
      // 只有在完全没有数据时才重置到第一页
      setCurrentPage(1);
      fetchSuggestions();
    } else {
      console.log('♻️ 使用已有的建议数据，当前页:', currentPage, '总页数:', totalPages);
      // 如果已有数据，不重置页面，保持用户当前的页面位置
    }
  }, [shouldFetchNewSuggestions, allSuggestions.length, currentPage, totalPages, fetchSuggestions]);

  // 隐藏建议面板
  const hideSuggestions = useCallback(() => {
    setIsVisible(false);
  }, []);

  // 刷新建议
  const refreshSuggestions = useCallback(() => {
    fetchSuggestions();
  }, [fetchSuggestions]);

  // 监听消息变化，当用户已打开建议面板时自动刷新
  useEffect(() => {
    const lastMessage = getLastMessage();
    if (lastMessage && isMessageFromAI(lastMessage)) {
      if (isVisible && lastMessage.messageServerId !== lastAiMessageId && allSuggestions.length > 0) {
        // 只有在面板已打开、收到新AI消息、且已有建议数据时才自动刷新
        // 这样避免了在首次打开面板时与 showSuggestions 中的调用冲突
        console.log('🔄 面板已打开，检测到新AI消息，自动刷新建议');
        fetchSuggestions();
      } else if (!isVisible) {
        // 面板未打开时只记录，不获取
        console.log('📨 检测到新的AI消息，但面板未打开，待用户打开时获取建议');
      }
    }
  }, [getLastMessage, isMessageFromAI, isVisible, lastAiMessageId, allSuggestions.length, fetchSuggestions]);

  // 监听当前页面数据加载完成，清除页面加载状态
  useEffect(() => {
    if (isPageLoading && loadedPages.has(currentPage)) {
      console.log('✅ 第', currentPage, '页数据加载完成，清除加载状态');
      setIsPageLoading(false);
    }
  }, [isPageLoading, loadedPages, currentPage]);

  return {
    suggestions: displaySuggestions, // 使用处理后的建议数据（包含骨架屏）
    currentPage,
    totalPages,
    isLoading,
    isVisible,
    isPageLoading, // 页面级别的加载状态
    isCurrentPageLoaded, // 当前页面是否已加载
    showSuggestions,
    hideSuggestions,
    handlePageChange,
    refreshSuggestions,
  };
};
