// 问答功能独立聊天页
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import { useLocalStorageState, useScroll } from 'ahooks'
import { Button } from '@heroui/react'
import { motion } from 'framer-motion'
import styles from '../Chat/Chat.module.less'
import { processApiResponse } from '../Chat/helper'
import { ChatItemUser } from '../Chat/components/ChatItem/ChatItemUser'
import { ChatAnswerBox } from '../Chat/components/ChatItem/ChatAnswerBox'
import { TacticsWelcome } from './components/TacticsWelcome'
import { ChatEditor } from '@/components/ChatEditor'
import type { ChatRecord } from '@/types/chat'
import { fetchTacticsQaRecordPage } from '@/api/tactics'
import { fetchCheckTokenApi, fetchStreamResponse } from '@/api/chat'
import { fetchLoginByToken, fetchLoginByUid } from '@/api/common'
import { clearTacticsNavigationFlag, clearTacticsShouldSendQuestion, createTacticsConversation, fetchTacticsConversations } from '@/store/tacticsSlice'
import type { RootState } from '@/store'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import ScrollBtoIcon from '@/assets/svg/scrollBto.svg?react'
import { setIsAsking } from '@/store/chatSlice'
import SdreamLoading from '@/components/SdreamLoading'

export const TacticsChat: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const location = useLocation()
  const navigate = useNavigate()
  const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'
  const [isLoading, setIsLoading] = useState(false)
  const [allItems, setAllItems] = useState<ChatRecord[]>([])
  const dispatch = useAppDispatch()
  const {
    shouldSendQuestion: shouldSendQuestionFromState,
    shouldNavigateToNewConversation,
    currentConversationId,
  } = useAppSelector((state: RootState) => state.tactics)
  const hasFetched = useRef(false)
  const hasCreatedRef = useRef(false)
  // 使用 useLocalStorageState 管理 token，与原有逻辑保持一致
  const [token, setToken] = useLocalStorageState<string | undefined>('__TOKEN__', {
    defaultValue: '',
  })
  // 优先从 location.state 获取，其次从 Redux state 获取
  const shouldSendQuestion = (location.state as { shouldSendQuestion?: string } | null)?.shouldSendQuestion || shouldSendQuestionFromState
  const scrollableRef = useRef<HTMLDivElement | any>(null)
  const position = useScroll(scrollableRef)
  const currentIdRef = useRef<string | undefined>(id)
  const lastSentQuestionRef = useRef<string>('')
  const abortControllerRef = useRef<AbortController | null>(null)

  // 创建新会话（仅在 tactics 聊天页面且没有 id 时调用）
  const initTacticsConversation = useCallback(() => {
    // 只有在 tactics 聊天页面且没有会话 id 时才创建新对话
    if (!id && location.pathname.startsWith('/tactics/chat')) {
      if (hasCreatedRef.current) {
        return
      }
      hasCreatedRef.current = true
      dispatch(
        createTacticsConversation({
          conversationData: {},
          shouldNavigate: true,
          shouldSendQuestion: '',
        }),
      )
    }
  }, [id, location.pathname, dispatch])

  // 登录逻辑（复用原有逻辑，与 TacticsHome.tsx 保持一致）
  const login = useCallback(async () => {
    if (hasFetched.current) {
      return
    }
    hasFetched.current = true
    const url = new URL(window.location.href)
    const searchParams = new URLSearchParams(url.search)
    const _loginCode = searchParams.get('loginCode')
    let res = {} as any
    if (viteOutputObj === 'inner') {
      if (_loginCode) {
        res = await fetchLoginByToken(_loginCode)
        if (res.data) {
          setToken(res.data.token)
          window.dispatchEvent(
            new StorageEvent('storage', {
              key: '__TOKEN__',
              oldValue: token,
              newValue: res.data.token,
              url: window.location.href,
              storageArea: localStorage,
            }),
          )
          // 登录成功后，如果是 tactics 聊天页面且没有 id，则创建会话
          initTacticsConversation()
          dispatch(fetchTacticsConversations())
        }
      }
      else {
        // 如果没有 loginCode，但已有 token，直接尝试创建会话
        initTacticsConversation()
        dispatch(fetchTacticsConversations())
      }
    }
    else {
      res = await fetchLoginByUid('123123')
      if (res.data) {
        setToken(res.data.token)
        window.dispatchEvent(
          new StorageEvent('storage', {
            key: '__TOKEN__',
            oldValue: token,
            newValue: res.data.token,
            url: window.location.href,
            storageArea: localStorage,
          }),
        )
        // 登录成功后，如果是 tactics 聊天页面且没有 id，则创建会话
        initTacticsConversation()
        dispatch(fetchTacticsConversations())
      }
    }
  }, [setToken, dispatch, token, initTacticsConversation, viteOutputObj])

  /** 处理正常stream的数据 */
  const handleStreamMesageData = (msg: any, question: string) => {
    setAllItems((prevItems) => {
      const newItems = [...prevItems]
      const lastIndex = newItems.length - 1
      if (lastIndex >= 0) {
        const originalAnswer = (newItems[lastIndex].answerList?.[0]?.answer || '') + msg.content.data.answer
        let filteredAnswer = originalAnswer.replace(/\([^)]*\)/g, '').trim()
        filteredAnswer = filteredAnswer.replace(/\[参考文档(?:《[^》]*》\s*)+\]/g, '').trim()

        newItems[lastIndex] = {
          ...newItems[lastIndex],
          question,
          answerList: [
            {
              ...msg.content.data,
              isShow: false,
              answer: filteredAnswer,
            },
          ],
        }
      }
      return newItems
    })
  }

  /** 处理超过最大条数的数据 */
  const handleChatMaxCount = (msg: any, question: string) => {
    setAllItems((prevItems) => {
      const newItems = [...prevItems]
      const lastIndex = newItems.length - 1
      if (lastIndex >= 0) {
        newItems[lastIndex] = {
          ...newItems[lastIndex],
          question,
          answerList: [
            {
              ...msg.content.data,
              isShow: false,
              isChatMaxCount: true,
              endAnswerFlag: true,
              answer: '已达上限',
            },
          ],
        }
      }
      return newItems
    })
  }

  /** 提交问题 */
  const handleSubmitQuestion = async (question: string) => {
    // 停止之前的请求
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
    }

    const isNew = allItems.length <= 1
    dispatch(setIsAsking(true))

    // 检查token
    await fetchCheckTokenApi()

    // 一次性添加用户问题和空的AI回答
    setAllItems(prevItems => [
      ...prevItems,
      {
        role: 'user',
        question,
      } as ChatRecord,
      {
        role: 'ai',
        answerList: [{ answer: '' }],
      } as ChatRecord,
    ])

    // 创建新的 AbortController
    abortControllerRef.current = new AbortController()

    let fetchUrl = `/conversation/api/conversation/mobile/v1/submit_question_stream`

    const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'

    let proxy = ''
    if (viteOutputObj === 'open') {
      proxy = import.meta.env.MODE !== 'prod' ? '/api' : '/dev-sdream-api'
    }
    else {
      proxy = import.meta.env.MODE === 'dev' ? '/api' : '/dev-sdream-api'
    }

    fetchUrl = proxy + fetchUrl

    fetchStreamResponse(
      fetchUrl,
      {
        question,
        conversationId: currentIdRef.current,
        stream: true,
      },
      (msg) => {
        // 检查是否已被取消
        if (abortControllerRef.current?.signal.aborted) {
          return
        }

        // 处理错误
        if (msg?.type === 'ERROR') {
          if (msg.content?.name === 'AbortError') {
            return
          }
          return
        }

        // 正常的stream数据
        if (msg?.type === 'DATA' && msg?.content?.code === '00000000') {
          handleStreamMesageData(msg, question)
        }
        if (msg?.type === 'DATA' && msg?.content?.code === '01010005') {
          handleChatMaxCount(msg, question)
          return
        }
        if (msg.type === 'END') {
          dispatch(setIsAsking(false))
          if (isNew) {
            setTimeout(() => {
              // 可以在这里刷新会话列表
            }, 2000)
          }
        }
      },
      abortControllerRef.current.signal,
    )
  }

  /** 获取qa记录 */
  const getUserQaRecordPage = useCallback(async (conversationId: string) => {
    setIsLoading(true)
    try {
      const res = await fetchTacticsQaRecordPage(conversationId)
      const qaRecords = res.data || []
      // 始终添加 system 角色作为欢迎语
      const messages = [{ role: 'system' } as ChatRecord, ...processApiResponse(qaRecords)]
      // 处理历史记录中的参考文档标记
      const processedMessages = messages.map((item) => {
        if (item.role === 'ai' && item.answerList?.[0]?.answer) {
          return {
            ...item,
            answerList: item.answerList.map(answerItem => ({
              ...answerItem,
              answer: answerItem.answer
                ?.replace(/\([^)]*\)/g, '')
                .replace(/\[参考文档(?:《[^》]*》\s*)+\]/g, '')
                .trim(),
            })),
          }
        }
        return item
      })
      setAllItems(processedMessages)
    }
    catch {
      // 如果获取失败，至少显示欢迎语
      setAllItems([{ role: 'system' } as ChatRecord])
    }
    finally {
      setIsLoading(false)
    }
  }, [])

  /** 点击滚动到底部 */
  const scrollToBottom = () => {
    scrollableRef.current.scrollTo(scrollableRef.current.scrollHeight, { behavior: 'smooth' })
  }

  useEffect(() => {
    if (id) {
      // 停止之前的请求
      if (abortControllerRef.current) {
        abortControllerRef.current.abort()
        dispatch(setIsAsking(false))
      }

      currentIdRef.current = id
      lastSentQuestionRef.current = ''
      getUserQaRecordPage(id)
    }
    else {
      // 如果没有 id，显示欢迎语，等待登录成功后创建新会话
      setAllItems([{ role: 'system' } as ChatRecord])
      setIsLoading(false)
    }
  }, [id, getUserQaRecordPage, dispatch])

  // 初始化时调用登录（登录成功后会自动创建会话）
  useEffect(() => {
    login()
  }, [login])

  // 创建新会话成功后跳转到新会话页面
  useEffect(() => {
    if (shouldNavigateToNewConversation && currentConversationId) {
      navigate(`/tactics/chat/${currentConversationId}`)
      dispatch(clearTacticsNavigationFlag())
    }
  }, [shouldNavigateToNewConversation, currentConversationId, navigate, dispatch])

  // 处理shouldSendQuestion的变化 - 自动发送问题
  useEffect(() => {
    if (
      shouldSendQuestion
      && currentIdRef.current
      && !isLoading
      && shouldSendQuestion !== lastSentQuestionRef.current
    ) {
      lastSentQuestionRef.current = shouldSendQuestion
      dispatch(clearTacticsShouldSendQuestion())
      setTimeout(() => {
        handleSubmitQuestion(shouldSendQuestion)
      }, 100)
    }
  }, [shouldSendQuestion, isLoading, dispatch])

  return (
    <div
      className={styles.scrollView}
      style={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        width: '420px',
        marginLeft: 'auto',
        marginRight: 0,
        position: 'fixed',
        right: 0,
        top: 0,
        backgroundColor: '#FFFFFF',
        zIndex: 1000,
      }}
    >
      <div className={`${styles.chatPage} relative flex flex-col h-full`}>
        <div className={`${styles.content} flex-1 overflow-hidden flex flex-col`}>
          {isLoading && (
            <div className="w-full h-full flex justify-center items-center">
              <SdreamLoading />
            </div>
          )}
          {!isLoading && (
            <motion.div
              ref={scrollableRef}
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{
                duration: 0.3,
                opacity: { duration: 0.1 },
              }}
              className={`${styles.scrollable} scrollbar-hide scroll-smooth flex-1 overflow-y-auto px-[16px]`}
            >
              <div className={`${styles.inter} py-[24px]`}>
                {allItems.map((record, index) => {
                  const recordId = record.answerList?.[0]?.recordId || record.groupId
                  const uniqueKey = recordId
                    ? `${record.role}-${recordId}`
                    : `${record.role}-${record.question || record.answerList?.[0]?.answer || ''}-${index}`
                  return (
                    <div
                      className="w-full chatItem mx-auto"
                      key={uniqueKey}
                    >
                      {record.role === 'system' && <TacticsWelcome />}
                      {record.role === 'user' && <ChatItemUser record={record} />}
                      {record.role === 'ai' && (
                        <ChatAnswerBox
                          onSubmitQuestion={handleSubmitQuestion}
                          isLastAnswer={index === allItems.length - 1}
                          showIndex={0}
                          record={record}
                          index={index}
                        />
                      )}
                    </div>
                  )
                })}
              </div>
            </motion.div>
          )}
        </div>
        <div className="relative box-border px-[16px] mx-auto iptContainer w-full flex-shrink-0 pb-[18px] pt-[12px] bg-white border-t border-gray-100">
          <div className="relative">
            <div className="absolute left-1/2 ml-[-20px] top-[-45px]">
              <motion.div
                initial="hidden"
                animate={(position?.top as number) < -20 ? 'visible' : 'hidden'}
                variants={{
                  hidden: { opacity: 0, y: 20, pointerEvents: 'none' as const },
                  visible: { opacity: 1, y: 0, pointerEvents: 'auto' as const },
                }}
                transition={{ duration: 0.3, ease: 'easeInOut' }}
              >
                <Button onPress={scrollToBottom} radius="full" isIconOnly color="primary">
                  <ScrollBtoIcon />
                </Button>
              </motion.div>
            </div>
            <ChatEditor
              onSubmit={handleSubmitQuestion}
              placeholders={[]}
              hideTools
            />
            <div className="w-full text-center mt-[12px] text-[#3333334d] text-[12px]">
              内容由AI模型生成，其准确性和完整性无法保证，仅供参考
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
