// 问答功能独立首页
import type React from 'react'
import { useCallback, useEffect, useRef } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useLocalStorageState } from 'ahooks'
import styles from '../Home/Home.module.less'
import { TacticsWelcome } from './components/TacticsWelcome'
import { clearTacticsNavigationFlag, createTacticsConversation, deleteTacticsConversations, fetchTacticsConversations } from '@/store/tacticsSlice'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import type { RootState } from '@/store'
import { fetchLoginByToken, fetchLoginByUid } from '@/api/common'
import { getUserRolesFromRoute } from '@/lib/utils'
import { ChatEditor } from '@/components/ChatEditor'
import { RECOMMEND_QUESTIONS_OTHER } from '@/config/recommendQuestion'
import { fetchCheckTokenApi, fetchStreamResponse } from '@/api/chat'
import DeleteIcon from '@/assets/svg/delete.svg?react'
import RefreshIcon from '@/assets/svg/refresh.svg?react'

export const TacticsHome: React.FC = () => {
  const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'
  const dispatch = useAppDispatch()
  const location = useLocation()
  const navigate = useNavigate()
  const hasFetched = useRef(false)
  const { shouldNavigateToNewConversation, currentConversationId, shouldSendQuestion } = useAppSelector((state: RootState) => state.tactics)

  const [token, setToken] = useLocalStorageState<string | undefined>('__TOKEN__', {
    defaultValue: '',
  })
  const abortControllerRef = useRef<AbortController | null>(null)

  const initTacticsConversation = () => {
    const fromCollect = location.state?.fromCollect
    // 只有在访问问答首页时才创建新对话
    if (!fromCollect && location.pathname === '/tactics') {
      dispatch(
        createTacticsConversation({
          conversationData: {},
          shouldNavigate: true,
          shouldSendQuestion: '',
        }),
      )
    }
    // 清除状态以避免下次影响
    if (location.state?.fromCollect) {
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  }

  // 处理创建对话并跳转（用于输入框提交）
  const handleCreateConversation = useCallback(async (question: string) => {
    // 如果已有会话，直接调用 submit 接口提交问题，然后跳转到聊天页面
    if (currentConversationId) {
      // 停止之前的请求
      if (abortControllerRef.current) {
        abortControllerRef.current.abort()
      }

      // 检查token
      await fetchCheckTokenApi()

      // 创建新的 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

      // 直接调用 submit 接口（消息流会在聊天页面处理，这里只负责发起请求）
      fetchStreamResponse(
        fetchUrl,
        {
          question,
          conversationId: currentConversationId,
          stream: true,
        },
        () => {
          // 在首页不需要处理消息，跳转到聊天页面后会自动刷新加载最新消息
        },
        abortControllerRef.current.signal,
      )

      // 跳转到聊天页面查看结果
      navigate(`/tactics/chat/${currentConversationId}`)
      return
    }
    // 如果没有会话，才创建新会话
    dispatch(
      createTacticsConversation({
        conversationData: {},
        shouldNavigate: true,
        shouldSendQuestion: question,
      }),
    )
  }, [dispatch, currentConversationId, navigate])

  // 监听导航到新对话
  useEffect(() => {
    if (shouldNavigateToNewConversation && currentConversationId) {
      const url = `/tactics/chat/${currentConversationId}`
      navigate(url, {
        state: {
          shouldSendQuestion,
        },
      })
      dispatch(clearTacticsNavigationFlag())
    }
  }, [shouldNavigateToNewConversation, currentConversationId, shouldSendQuestion, navigate, dispatch])

  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,
            }),
          )
          initTacticsConversation()
          dispatch(fetchTacticsConversations())
        }
      }
      else {
        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,
          }),
        )
        initTacticsConversation()
        dispatch(fetchTacticsConversations())
      }
    }
  }, [setToken, dispatch, token])

  // 监听路由参数变化
  useEffect(() => {
    getUserRolesFromRoute()
  }, [location.search])

  useEffect(() => {
    login()
  }, [])

  // 处理清除记录
  const handleClearRecord = useCallback(async () => {
    if (!currentConversationId) {
      return
    }
    try {
      await dispatch(deleteTacticsConversations([currentConversationId])).unwrap()
      // 清除后创建新会话
      dispatch(
        createTacticsConversation({
          conversationData: {},
          shouldNavigate: false,
          shouldSendQuestion: '',
        }),
      )
    }
    catch (error) {
      console.error('清除记录失败:', error)
    }
  }, [currentConversationId, dispatch])

  // 处理重新分析
  const handleReanalyze = useCallback(async () => {
    // 重新获取会话列表
    await dispatch(fetchTacticsConversations())
    // 如果有当前会话，可以重新加载
    if (currentConversationId) {
      navigate(`/tactics/chat/${currentConversationId}`)
    }
  }, [currentConversationId, dispatch, navigate])

  return (
    <div
      className={styles.homePage}
      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="flex justify-end items-center gap-[16px] px-[16px] pt-[16px] pb-[8px]">
        <button
          type="button"
          onClick={handleClearRecord}
          className="flex items-center gap-[4px] text-[#4A90E2] text-[14px] hover:opacity-80 transition-opacity cursor-pointer bg-transparent border-none outline-none"
        >
          <DeleteIcon className="w-[16px] h-[16px] text-[#B2B8C1]" />
          <span>清除记录</span>
        </button>
        <button
          type="button"
          onClick={handleReanalyze}
          className="flex items-center gap-[4px] text-[#4A90E2] text-[14px] hover:opacity-80 transition-opacity cursor-pointer bg-transparent border-none outline-none"
        >
          <RefreshIcon className="w-[16px] h-[16px] text-[#B2B8C1]" />
          <span>重新分析</span>
        </button>
      </div>

      <div className="h-full w-full flex flex-col">
        {/* 主要内容区域 - 全屏显示 */}
        <div className="flex-1 overflow-hidden flex flex-col">
          {/* 欢迎语区域 */}
          <div className="flex-1 overflow-y-auto scrollbar-hide px-[16px] pt-[24px]">
            <TacticsWelcome />
          </div>
          {/* 底部输入框 */}
          <div className="box-border px-[16px] pb-[18px] pt-[12px] bg-white border-t border-gray-100">
            <ChatEditor
              showContentTips
              onSubmit={handleCreateConversation}
              placeholders={RECOMMEND_QUESTIONS_OTHER}
              hideTools
            />
            <div className="w-full text-center mt-[12px] text-[#3333334d] text-[12px]">
              内容由AI模型生成，其准确性和完整性无法保证，仅供参考
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
