// 问答功能独立首页
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 { ChatWelcome } from '../Chat/components/ChatWelcome'
import { clearTacticsNavigationFlag, createTacticsConversation, 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'

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 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((question: string) => {
    dispatch(
      createTacticsConversation({
        conversationData: {},
        shouldNavigate: true,
        shouldSendQuestion: question,
      }),
    )
  }, [dispatch])

  // 监听导航到新对话
  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()
  }, [])

  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="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]">
            <ChatWelcome />
          </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>
  )
}
