// 问答功能独立首页
import type React from 'react'
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { useLocalStorageState } from 'ahooks'
import styles from '../Home/Home.module.less'
import { TacticsWelcome } from './components/TacticsWelcome'
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 { TacticsChatEditor } from '@/components/TacticsChatEditor'

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

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

  // 仅在 from=tactics 且 version=2 时读取并缓存额外参数
  const tacticsMetaFromSearch = useMemo(() => {
    const from = searchParams.get('from')
    const version = searchParams.get('version')
    if (from !== 'tactics' || version !== '2') {
      return undefined
    }
    return {
      version,
      taskId: searchParams.get('taskId') || undefined,
      pinBeginTime: searchParams.get('pinBeginTime') || undefined,
      pinEndTime: searchParams.get('pinEndTime') || undefined,
      partOrAll: searchParams.get('partOrAll') || undefined,
      channel: searchParams.get('channel') || undefined,
      channelName: searchParams.get('channelName') || undefined,
    }
  }, [searchParams])
  const tacticsMetaFromStorage = useMemo(() => {
    const raw = sessionStorage.getItem('tacticsMeta')
    if (!raw) {
      return undefined
    }
    try {
      const parsed = JSON.parse(raw)
      if (parsed?.from === 'tactics' && parsed?.version === '2') {
        return parsed
      }
    }
    catch {
      // ignore
    }
    return undefined
  }, [])
  const tacticsMeta = useMemo(() => tacticsMetaFromSearch || tacticsMetaFromStorage, [tacticsMetaFromSearch, tacticsMetaFromStorage])

  // 同步到 sessionStorage，便于跳转后读取；仅在有 meta 时写入，避免覆盖重定向缓存
  useEffect(() => {
    if (tacticsMeta) {
      sessionStorage.setItem('tacticsMeta', JSON.stringify(tacticsMeta))
    }
  }, [tacticsMeta])

  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) {
      navigate(`/tactics/chat/${currentConversationId}`, {
        state: {
          shouldSendQuestion: question,
          tacticsMeta,
        },
      })
      return
    }
    // 如果没有会话，才创建新会话
    dispatch(
      createTacticsConversation({
        conversationData: {},
        shouldNavigate: true,
        shouldSendQuestion: question,
      }),
    )
  }, [dispatch, currentConversationId, navigate, tacticsMeta])

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

  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',
        marginLeft: 'auto',
        marginRight: 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]">
            <TacticsWelcome />
          </div>
          {/* 底部输入框 */}
          <div className="box-border px-[16px] pb-[18px] pt-[12px] bg-white border-t border-gray-100">
            <TacticsChatEditor
              onSubmit={handleCreateConversation}
              placeholders={['']}
            />
            <div className="w-full text-center mt-[12px] text-[#3333334d] text-[12px]">
              内容由AI模型生成，其准确性和完整性无法保证，仅供参考
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
