// 问答功能独立首页
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')
    if (from !== 'tactics') {
      return undefined
    }
    const taskId = searchParams.get('taskId') || undefined
    return {
      version: searchParams.get('version'),
      taskId,
      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,
      // 新建会话需要的业务识别参数
      busiType: '02',
      busiId: taskId,
    }
  }, [searchParams])
  const tacticsMetaFromStorage = useMemo(() => {
    const raw = sessionStorage.getItem('tacticsMeta')
    if (!raw) {
      return undefined
    }
    try {
      const parsed = JSON.parse(raw)
      if (parsed?.from === 'tactics') {
        return parsed
      }
    }
    catch {
      // ignore
    }
    return undefined
  }, [])
  const tacticsMeta = useMemo(() => tacticsMetaFromSearch || tacticsMetaFromStorage, [tacticsMetaFromSearch, tacticsMetaFromStorage])

  // 读取 place=user 时的 userMeta 参数
  const userMetaFromSearch = useMemo(() => {
    const place = searchParams.get('place')
    if (place !== 'user') {
      return undefined
    }
    return {
      place,
      cstId: searchParams.get('cstId') || undefined,
      userId: searchParams.get('userId') || undefined,
      numberType: searchParams.get('numberType') || undefined,
      busiType: '02',
      busiId: searchParams.get('userId') || undefined,
    }
  }, [searchParams])
  const userMetaFromStorage = useMemo(() => {
    const raw = sessionStorage.getItem('userMeta')
    if (!raw) {
      return undefined
    }
    try {
      const parsed = JSON.parse(raw)
      if (parsed?.place === 'user') {
        return parsed
      }
    }
    catch {
      // ignore
    }
    return undefined
  }, [])
  const userMeta = useMemo(() => userMetaFromSearch || userMetaFromStorage, [userMetaFromSearch, userMetaFromStorage])

  // 仅用于创建会话的额外参数（对应 create_conversation）
  const getConversationExtra = useCallback(() => {
    if (userMeta?.place === 'user') {
      return {
        busiType: '02',
        busiId: userMeta.userId,
      }
    }
    if (tacticsMeta) {
      return {
        busiType: '02',
        busiId: tacticsMeta.taskId,
      }
    }
    return {}
  }, [tacticsMeta, userMeta])

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

  // 同步 userMeta 到 sessionStorage
  useEffect(() => {
    if (userMeta) {
      sessionStorage.setItem('userMeta', JSON.stringify(userMeta))
    }
  }, [userMeta])

  const initTacticsConversation = () => {
    const fromCollect = location.state?.fromCollect
    // 只有在访问问答首页时才创建新对话
    if (!fromCollect && location.pathname === '/tactics') {
      dispatch(
        createTacticsConversation({
          conversationData: getConversationExtra(),
          shouldNavigate: true,
          shouldSendQuestion: '',
        }),
      )
        .unwrap()
        .then((res) => {
          const conversationId = res?.conversation?.id
          const from = searchParams.get('from')
          const place = searchParams.get('place')
          if (conversationId && from === 'tactics') {
            const storageKey = place === 'user' ? 'tactics_user_conversation_id' : 'tactics_conversation_id'
            window.localStorage.setItem(storageKey, conversationId)
          }
          // eslint-disable-next-line no-console
          console.log('[TacticsHome] created conversationId', conversationId)
        })
    }
    // 清除状态以避免下次影响
    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,
          userMeta,
        },
      })
      return
    }
    // 如果没有会话，才创建新会话
    dispatch(
      createTacticsConversation({
        conversationData: getConversationExtra(),
        shouldNavigate: true,
        shouldSendQuestion: question,
      }),
    )
  }, [dispatch, currentConversationId, navigate, tacticsMeta, userMeta, getConversationExtra])

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

  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>
  )
}
