import type React from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { motion } from 'framer-motion'
import { Outlet, useLocation } from 'react-router-dom'
import { useLocalStorageState } from 'ahooks'
import styles from './Home.module.less'
import { QuestionList } from './components/QuestionList'
import HomeIcon2 from '@/assets/homeIcon2.png'
import SmartIce from '@/assets/smart-ice.png'
import { clearCurrentToolId, createConversation, fetchConversations, setCurrentConversation, setCurrentToolId, setNavigationFlag } from '@/store/conversationSlice'
import { useAppDispatch } from '@/store/hook'
import { fetchEfficiencyQuestionList } from '@/api/home'
import SdreamLoading from '@/components/SdreamLoading'
import { fetchLoginByToken, fetchLoginByUid } from '@/api/common'
import { getUserRolesFromRoute, safeLocalStorageGetItem, safeSessionStorageGetItem, safeSessionStorageRemoveItem, safeSessionStorageSetItem } from '@/lib/utils'
import type { Conversation } from '@/types/conversation'

function getAnimationProps(delay: number) {
  return {
    variants: {
      hidden: {
        opacity: 0,
        y: 50,
        scale: 0.9,
        rotateX: -6,
      },
      visible: {
        opacity: 1,
        y: 0,
        scale: 1,
        rotateX: 0,
        transition: {
          duration: 0.4,
          delay: delay * 0.1,
          ease: [0.25, 0.1, 0.25, 1],
        },
      },
    },
    initial: 'hidden',
    animate: 'visible',
  }
}

export const Home: React.FC = () => {
  const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'
  const [isLoading, _setIsLoading] = useState(false)
  const [isDataLoaded, setIsDataLoaded] = useState(false)
  const dispatch = useAppDispatch()
  const location = useLocation()
  const hasFetched = useRef(false)
  // 使用 useState
  const [otherQuestions, setOtherQuestions] = useState<any>({ content: [] })
  const [isToolBtnActive, setIsToolBtnActive] = useState<boolean>(false)
  const [shouldChangeStyle, setShouldChangeStyle] = useState<boolean>(true)
  // 保存原始的configType为07的数据
  const [originalOtherQuestions, _setOriginalOtherQuestions] = useState<any>({ content: [] })

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

  const initConversation = async () => {
    const fromCollect = location.state?.fromCollect
    // 只有在访问首页时才处理会话，如果已经在聊天页面则不处理
    if (!fromCollect && (location.pathname === '/' || location.pathname === '/home')) {
      // 从 localStorage 读取上次的 conversationId
      const savedConversationId = safeLocalStorageGetItem('currentConversationId')

      if (savedConversationId) {
        // 如果 localStorage 中有 conversationId，恢复它而不是创建新会话
        dispatch(setCurrentConversation(savedConversationId))
        // 设置导航标志，触发自动导航到聊天页面
        dispatch(setNavigationFlag(true))
        // 获取会话列表（用于后续验证和同步 toolId）
        const fetchResult = await dispatch(fetchConversations())
        const conversationsList = fetchResult.payload as Conversation[]

        // 同步会话的 toolId（如果存在）
        const restoredConversation = conversationsList?.find((conv: Conversation) => conv.conversationId === savedConversationId)
        if (restoredConversation?.toolId) {
          dispatch(setCurrentToolId(restoredConversation.toolId))
          // 同步到 sessionStorage，确保 ChatEditor 等组件能正确识别 toolId
          safeSessionStorageSetItem('currentToolId', restoredConversation.toolId)
        }
        else {
          dispatch(clearCurrentToolId())
          // 清除 sessionStorage 中的 toolId
          safeSessionStorageRemoveItem('currentToolId')
        }
      }
      else {
        // 如果 localStorage 中没有 conversationId，创建新会话
        dispatch(fetchConversations())
        dispatch(
          createConversation({
            conversationData: {},
            shouldNavigate: true,
            shouldSendQuestion: '',
          }),
        )
      }
    }
    // 清除状态以避免下次影响
    if (location.state?.fromCollect) {
      // 使用 replace 替换当前历史记录，清除 state
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  }

  // 刷新问题列表
  const handleRefreshQuestions = useCallback(async () => {
    // 先清空旧数据
    setOtherQuestions((prev: any) => ({
      ...prev,
      content: [],
    }))
    setIsDataLoaded(false) // 重置加载状态

    try {
      // 获取当前的 toolId，只从 sessionStorage 获取
      const sessionToolId = safeSessionStorageGetItem('currentToolId') || ''

      // 调用接口重新获取问题列表
      const res = await fetchEfficiencyQuestionList({
        toolId: sessionToolId,
      })
      if (res && res.data && res.data.questions) {
        setOtherQuestions((prev: any) => ({
          ...prev,
          content: res.data.questions || [],
        }))
      }
    }
    catch (error) {
      console.error('刷新问题列表失败:', error)
      throw error // 抛出错误，让 QuestionList 组件处理
    }
    finally {
      setIsDataLoaded(true) // 无论成功失败都标记为已加载
    }
  }, [location.search])

  // 处理工具按钮点击
  const _handleToolClick = useCallback(async (isToolBtn: boolean, toolId?: string, ignoreUrlToolId?: boolean) => {
    // 提质增效模式 / 数据助手 / 制度活化：都先清空数据，重新拉常见问题
    setOtherQuestions((prev: any) => ({
      ...prev,
      content: [],
    }))
    setIsDataLoaded(false) // 重置加载状态
    try {
      const storedToolId = safeSessionStorageGetItem('currentToolId') || ''
      // 首页初始化加载常见问题时，允许忽略路由中的 toolId，避免带入上一次的工具 ID
      const shouldForceClearToolId = !storedToolId

      let finalToolId = toolId || ''

      // 场景：首页首次挂载（ignoreUrlToolId === true）且为制度活化（!isToolBtn && !toolId）
      // 此时无论 sessionStorage 中是否残留上一次的 toolId，都强制使用空字符串，避免带入历史工具 ID
      if (ignoreUrlToolId && !isToolBtn && !toolId) {
        finalToolId = ''
      }
      else if (shouldForceClearToolId && !isToolBtn) {
        finalToolId = ''
      }
      else if (!finalToolId && !isToolBtn) {
        // 仅在工具模式下才使用回退逻辑，避免制度活化误用上一次的 toolId
        finalToolId = storedToolId
      }

      // 调用真实 API 获取常见问题列表，优先使用 sessionStorage 中的 currentToolId
      const sessionToolId = safeSessionStorageGetItem('currentToolId') || ''
      const res = await fetchEfficiencyQuestionList({
        toolId: sessionToolId || finalToolId,
      })
      if (res && res.data && res.data.questions) {
        setOtherQuestions((prev: any) => ({
          ...prev,
          content: res.data.questions || [],
        }))
      }
    }
    catch (error) {
      console.error('获取工具相关问题失败:', error)
    }
    finally {
      setIsDataLoaded(true) // 无论成功失败都标记为已加载
    }
  }, [originalOtherQuestions, location.search])

  // 监听工具按钮点击事件
  useEffect(() => {
    const handleToolClickEvent = (event: CustomEvent) => {
      const { isToolBtn, toolId } = event.detail
      setIsToolBtnActive(isToolBtn)
      // 更新样式控制状态
      setShouldChangeStyle(true)

      // 保存当前选择的 toolId 到 Redux
      if (!isToolBtn && toolId) {
        // 提质增效模式，保存 toolId
        dispatch(setCurrentToolId(toolId))
      }
      else {
        // 制度活化，清除 toolId
        dispatch(clearCurrentToolId())
      }

      _handleToolClick(isToolBtn, toolId)
    }
    window.addEventListener('toolButtonClick', handleToolClickEvent as EventListener)
    return () => {
      window.removeEventListener('toolButtonClick', handleToolClickEvent as EventListener)
    }
  }, [_handleToolClick, isToolBtnActive, shouldChangeStyle, 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) {
        // 每次进入页面调用 sso_login 时，先清空 sessionStorage 中的 currentToolId
        // 避免关闭标签页后再次打开时使用上次的历史 toolId
        safeSessionStorageRemoveItem('currentToolId')
        res = await fetchLoginByToken(_loginCode)
        if (res.data) {
          // 登录成功后先打印完整的原始链接（删除之前）
          // eslint-disable-next-line no-console
          console.log('20251211登录成功，删除前完整链接:', window.location.href)
          // 登录成功后先清理旧状态，避免沿用上一次的工具模式
          dispatch(clearCurrentToolId())
          safeSessionStorageRemoveItem('currentToolId')
          const currentUrl = new URL(window.location.href)
          if (currentUrl.searchParams.has('toolId')) {
            currentUrl.searchParams.delete('toolId')
            // 使用 replace 避免产生新的历史记录
            window.history.replaceState({}, '', currentUrl.toString())
          }
          // 删除后打印链接
          // eslint-disable-next-line no-console
          console.log('20251211登录成功，删除后完整链接:', window.location.href)
          setToken(res.data.token)
          // 主动触发 storage 事件，确保其他组件能监听到变化
          window.dispatchEvent(
            new StorageEvent('storage', {
              key: '__TOKEN__',
              oldValue: token,
              newValue: res.data.token,
              url: window.location.href,
              storageArea: localStorage,
            }),
          )
          // 触发自定义事件，通知 ChatEditor 强制重置为制度活化
          window.dispatchEvent(new CustomEvent('forceResetToGeneralMode'))
          initConversation()
          dispatch(fetchConversations())
          // 2. 拉取常见问题等业务数据
          _handleToolClick(false, '', true)
        }
      }
      else {
        initConversation()
        dispatch(fetchConversations())
      }
    }
    else {
      // 模拟登录 可以用来测试
      res = await fetchLoginByUid('123123')
      if (res.data) {
        // 登录成功后先清理旧状态，避免沿用上一次的工具模式
        dispatch(clearCurrentToolId())
        safeSessionStorageRemoveItem('currentToolId')
        const currentUrl = new URL(window.location.href)
        if (currentUrl.searchParams.has('toolId')) {
          currentUrl.searchParams.delete('toolId')
          window.history.replaceState({}, '', currentUrl.toString())
        }
        setToken(res.data.token)
        // 主动触发 storage 事件，确保其他组件能监听到变化
        window.dispatchEvent(
          new StorageEvent('storage', {
            key: '__TOKEN__',
            oldValue: token,
            newValue: res.data.token,
            url: window.location.href,
            storageArea: localStorage,
          }),
        )
        // 触发自定义事件，通知 ChatEditor 强制重置为制度活化
        window.dispatchEvent(new CustomEvent('forceResetToGeneralMode'))
        initConversation()
        dispatch(fetchConversations())
            // 2. 拉取常见问题等业务数据
        _handleToolClick(false, '', true)
      }
    }
  }, [setToken, dispatch])

  // 监听路由参数变化，提取 userRoles（确保路由参数被正确解析）
  useEffect(() => {
    getUserRolesFromRoute()
  }, [location.search])

  useEffect(() => {
    login()
  }, []) // 依赖数组为空，只在组件挂载时执行一次

  useEffect(() => {
    // 只有登录成功（拿到 token）后才拉业务接口
    if (!token)
      return
    dispatch(clearCurrentToolId())
  }, [token, dispatch])

  return (
    <div className={styles.homePage}>
      {isLoading && (
        <div className="w-full h-full flex justify-center items-center">
          <SdreamLoading />
        </div>
      )}
      <div className="h-full w-full">
        <div className="box flex flex-col h-full w-full">
          <div className="flex-1 items-center pt-[24px] sm:pt-[32px] scrollbar-hide">
            <div className="w-full">
              <div className="flex justify-center gap-[20px]">
                {/* 左侧区域 - 产品问答和您可以试着问我 */}
                  <div
                    className="flex flex-col gap-[20px] items-center overflow-y-auto scrollbar-hide"
                    style={{ height: shouldChangeStyle ? 'calc(-64px + 100vh)' : '500px', background: shouldChangeStyle ? 'linear-gradient(180deg, #DEF6FF 0%, #FFFFFF 50%, #FFFFFF 100%)' : '', borderRadius: '24px' }}
                  >
                {/* {!shouldChangeStyle && (
                  <motion.div className="w-full sm:w-auto" {...getAnimationProps(2)}>
                    <QuestionList
                      questions={productQuestions.content}
                      dotColor="#D4CCFF"
                      background="linear-gradient(180deg, #EBE6FF 0%, #FFFFFF 50%, #FFFFFF 100%)"
                      title={productQuestions.configName}
                      iconImg={HomeIcon1}
                      isToolBtn={shouldChangeStyle}
                      isLoaded={isDataLoaded}
                    />
                  </motion.div>
                )} */}
                  <motion.div className="w-full sm:w-auto" {...getAnimationProps(3)}>
                    <QuestionList
                      questions={otherQuestions.content}
                      dotColor="#CBECFF"
                      background="linear-gradient(180deg, #DEF6FF 0%, #FFFFFF 50%, #FFFFFF 100%)"
                      height={shouldChangeStyle ? '288px' : 'auto'}
                      title={otherQuestions.configName}
                      iconImg={HomeIcon2}
                      isToolBtn={shouldChangeStyle}
                      isLoaded={isDataLoaded}
                      onRefresh={handleRefreshQuestions}
                    />
                  </motion.div>
                  {shouldChangeStyle && (
                    <div className="w-full flex justify-center mt-auto pb-[24px]">
                      <img src={SmartIce} alt="Smart Ice" className="w-[260px] h-[218px] mt-[-12px] object-contain" />
                    </div>
                  )}
                  </div>
                {/* 右侧区域 */}
                <div className="hidden sm:flex flex-1 h-full">
                  <div
                    className="w-full h-full bg-transparent box-border rounded-[24px]"
                    style={{ height: 'calc(100vh - 64px)', background: '#FFFFFF', padding: '0 30px' }}
                  >
                    <Outlet />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
