// 问答功能独立首页
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 { getUserRolesFromRoute, safeLocalStorageGetItem, waitForToken } from '@/lib/utils'
import { TacticsChatEditor } from '@/components/TacticsChatEditor'

export const TacticsHome: React.FC = () => {
  const dispatch = useAppDispatch()
  const location = useLocation()
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const { shouldNavigateToNewConversation, currentConversationId, shouldSendQuestion } = useAppSelector((state: RootState) => state.tactics)

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

  // from=tactics 时读取额外参数，用于新建会话（直接从 query 读取，不再使用 sessionStorage）
  const tacticsMeta = 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])

  // 读取 place=user 时的 userMeta 参数（直接从 query 读取，不再使用 sessionStorage）
  const userMeta = 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])

  // 读取 from=tactics&place=order 时的 orderMeta 参数（直接从 query 读取，不再使用 sessionStorage）
  const orderMeta = useMemo(() => {
    const from = searchParams.get('from')
    const place = searchParams.get('place')
    if (from !== 'tactics' || place !== 'order') {
      return undefined
    }
    // 打印完整链接
    console.log('[TacticsHome] from=tactics&place=order 完整链接:', window.location.href)
    return {
      workOrderIds: searchParams.get('workOrderIds') || undefined,
    }
  }, [searchParams])

  // 仅用于创建会话的额外参数（对应 create_conversation）
  const getConversationExtra = useCallback(() => {
    if (orderMeta) {
      // 从 localStorage 读取 userId
      const userIdFromStorage = safeLocalStorageGetItem('__USER_NAME__')
      let userId = ''
      if (userIdFromStorage) {
        try {
          // useLocalStorageState 会将值序列化为 JSON，需要解析
          const parsed = JSON.parse(userIdFromStorage)
          userId = parsed || userIdFromStorage
        }
        catch {
          // 如果不是 JSON 格式，直接使用原始值
          userId = userIdFromStorage
        }
      }
      return {
        busiType: '02',
        busiId: userId,
        workOrderIds: orderMeta.workOrderIds,
      } as Partial<any>
    }
    if (userMeta?.place === 'user') {
      return {
        busiType: '02',
        // place=user 场景下，业务方要求 busiId 取 userId:numberType，若numberType为空则只传userId
        busiId: userMeta.userId && userMeta.numberType
          ? `${userMeta.userId}:${userMeta.numberType}`
          : userMeta.userId || userMeta.numberType,
      } as Partial<any>
    }
    if (tacticsMeta) {
      return {
        busiType: '02',
        busiId: tacticsMeta.taskId,
      } as Partial<any>
    }
    return {} as Partial<any>
  }, [orderMeta, tacticsMeta, userMeta])

  const initTacticsConversation = async () => {
    const fromCollect = location.state?.fromCollect
    // 只有在访问问答首页时才创建新对话
    if (!fromCollect && location.pathname === '/tactics') {
      // 等待 token 就绪后再调用接口
      await waitForToken()
      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 fromValues = searchParams.getAll('from')
            let storageKey = 'tactics_conversation_id'
            if (fromValues.includes('order')) {
              storageKey = 'tactics_order_conversation_id'
            }
            else if (place === 'user') {
              storageKey = 'tactics_user_conversation_id'
            }
            window.localStorage.setItem(storageKey, 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}${location.search}`, {
        state: {
          shouldSendQuestion: question,
        },
      })
      return
    }
    // 如果没有会话，才创建新会话
    dispatch(
      createTacticsConversation({
        conversationData: getConversationExtra(),
        shouldNavigate: true,
        shouldSendQuestion: question,
      }),
    )
  }, [dispatch, currentConversationId, navigate, location.search, getConversationExtra])

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

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

  // 当 token 存在时，初始化会话和获取会话列表
  useEffect(() => {
    // 防止重复执行
    if (hasInitialized.current) {
      return
    }

    // 直接从 localStorage 读取 token，避免 state 更新延迟的问题
    const getTokenFromStorage = () => {
      const tokenFromStorage = safeLocalStorageGetItem('__TOKEN__')
      if (!tokenFromStorage) {
        return null
      }
      try {
        // useLocalStorageState 会将值序列化为 JSON，需要解析
        const parsed = JSON.parse(tokenFromStorage)
        return parsed || tokenFromStorage
      }
      catch {
        // 如果不是 JSON 格式，直接使用原始值
        return tokenFromStorage
      }
    }

    const actualToken = getTokenFromStorage() || token

    // 确保 token 存在后再执行业务逻辑
    if (actualToken) {
      hasInitialized.current = true
      // initTacticsConversation 内部已有 waitForToken 等待，这里直接调用
      initTacticsConversation()
      dispatch(fetchTacticsConversations())
    }
  }, [token, dispatch])

  // 监听 localStorage 中 token 的变化（处理跨组件 token 更新的情况）
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      // 防止重复执行（如果已经初始化过，不再执行）
      if (hasInitialized.current) {
        return
      }

      if (e.key === '__TOKEN__' && e.newValue) {
        // token 更新后，重新执行业务逻辑
        let actualToken = null
        try {
          const parsed = JSON.parse(e.newValue)
          actualToken = parsed || e.newValue
        }
        catch {
          actualToken = e.newValue
        }

        if (actualToken) {
          hasInitialized.current = true
          // initTacticsConversation 内部已有 waitForToken 等待，这里直接调用
          initTacticsConversation()
          dispatch(fetchTacticsConversations())
        }
      }
    }

    window.addEventListener('storage', handleStorageChange)
    return () => {
      window.removeEventListener('storage', handleStorageChange)
    }
  }, [dispatch])

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