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, setCurrentToolId } from '@/store/conversationSlice'
import { useAppDispatch } from '@/store/hook'
import { fetchEfficiencyQuestionList, fetchQuestionList } from '@/api/home'
import SdreamLoading from '@/components/SdreamLoading'
import { fetchLoginByToken, fetchLoginByUid } from '@/api/common'

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: [] })
  // 保存原始的configType为07的数据
  const [originalOtherQuestions, setOriginalOtherQuestions] = useState<any>({ content: [] })

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

  const fetchGeneralQuestions = useCallback(
    async (fallbackData?: any) => {
      try {
        const res = await fetchEfficiencyQuestionList({ toolId: '' })
        if (res && res.data && res.data.questions) {
          setOtherQuestions((prev: any) => ({
            ...prev,
            content: res.data.questions || [],
          }))
          return
        }
      }
      catch (error) {
        console.error('获取通用问题失败:', error)
      }
      // 如果接口无数据或失败，显示空态但保留基础信息
      const baseData = fallbackData || originalOtherQuestions
      setOtherQuestions((prev: any) => ({
        ...prev,
        ...baseData,
        content: [],
      }))
    },
    [originalOtherQuestions],
  )

  /** 获取qa记录 */
  const getQuestionList = useCallback(async () => {
    setIsLoading(true)
    try {
      const param = {
        configTypeList: ['06', '07'],
      }
      const res = await fetchQuestionList(param)
      if (res && res.data) {
        for (let index = 0; index < res.data.length; index++) {
          const element = res.data[index]
          if (element.configType === '07') {
            element.content = JSON.parse(element.content)
            setOtherQuestions(element)
            setOriginalOtherQuestions(element) // 保存原始数据
            await fetchGeneralQuestions(element)
          }
        }
      }
    }
 catch (error) {
      // 可以在这里添加错误处理逻辑
      console.error('Failed to fetch chat records:', error)
    }
finally {
      setIsLoading(false)
      setIsDataLoaded(true)
    }
  }, [fetchGeneralQuestions])

  const initConversation = () => {
    const fromCollect = location.state?.fromCollect
    // 只有在访问首页时才创建新对话，如果已经在聊天页面则不创建
    if (!fromCollect && (location.pathname === '/' || location.pathname === '/home')) {
      dispatch(
        createConversation({
          conversationData: {},
          shouldNavigate: true,
          shouldSendQuestion: '',
        }),
      )
    }
    // 清除状态以避免下次影响
    if (location.state?.fromCollect) {
      // 使用 replace 替换当前历史记录，清除 state
      window.history.replaceState({}, document.title, window.location.pathname)
    }
  }

  // 处理工具按钮点击
  const _handleToolClick = useCallback(async (isToolBtn: boolean, toolId?: string) => {
    if (!isToolBtn && toolId) {
      // 提质增效模式：只修改左侧页面内容，加载工具相关问题
      // 先清空数据，确保显示空数据样式
      setOtherQuestions((prev: any) => ({
        ...prev,
        content: [],
      }))
      setIsDataLoaded(false) // 重置加载状态
      try {
        const res = await fetchEfficiencyQuestionList({ toolId })
        if (res && res.data && res.data.questions) {
          setOtherQuestions((prev: any) => ({
            ...prev,
            content: res.data.questions || [],
          }))
        }
      }
      catch (error) {
        console.error('获取工具相关问题失败:', error)
      }
      finally {
        setIsDataLoaded(true) // 无论成功失败都标记为已加载
      }
    }
    else if (isToolBtn) {
      // 通用模式：调用接口获取通用问题，toolId 传空字符串
      setIsDataLoaded(false)
      await fetchGeneralQuestions()
      setIsDataLoaded(true)
    }
  }, [originalOtherQuestions, fetchGeneralQuestions])

  // 进入页面时，如果路由中有 toolId 且不为空，执行工具点击逻辑
  useEffect(() => {
    if (location.pathname.startsWith('/chat/')) {
      const urlParams = new URLSearchParams(window.location.search)
      const toolIdFromUrl = urlParams.get('toolId')
      if (toolIdFromUrl && toolIdFromUrl !== '') {
        // 有 toolId，执行工具点击逻辑
        dispatch(setCurrentToolId(toolIdFromUrl))
        _handleToolClick(false, toolIdFromUrl)
      }
    }
  }, [location.pathname, location.search, dispatch, _handleToolClick])

  // 监听工具按钮点击事件
  useEffect(() => {
    const handleToolClickEvent = (event: CustomEvent) => {
      const { isToolBtn, toolId } = event.detail

      // 保存当前选择的 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, 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)
          // 主动触发 storage 事件，确保其他组件能监听到变化
          window.dispatchEvent(
            new StorageEvent('storage', {
              key: '__TOKEN__',
              oldValue: token,
              newValue: res.data.token,
              url: window.location.href,
              storageArea: localStorage,
            }),
          )
          await getQuestionList()
          initConversation()
          dispatch(fetchConversations())
        }
      }
 else {
        await getQuestionList()
        initConversation()
        dispatch(fetchConversations())
      }
    }
 else {
      // 模拟登录 可以用来测试
      res = await fetchLoginByUid('123123')
      if (res.data) {
        setToken(res.data.token)
        // 主动触发 storage 事件，确保其他组件能监听到变化
        window.dispatchEvent(
          new StorageEvent('storage', {
            key: '__TOKEN__',
            oldValue: token,
            newValue: res.data.token,
            url: window.location.href,
            storageArea: localStorage,
          }),
        )
        await getQuestionList()
        initConversation()
        dispatch(fetchConversations())
      }
    }
  }, [setToken])

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

  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: 'calc(-64px + 100vh)',
                      background: 'linear-gradient(180deg, #F0F8FF 0%, #FFFFFF 50%, #FFFFFF 100%)',
                      borderRadius: '24px',
                    }}
                  >
                  <motion.div className="w-full sm:w-auto" {...getAnimationProps(3)}>
                    <QuestionList
                      questions={otherQuestions.content}
                      dotColor="#CBECFF"
                      background="linear-gradient(180deg, #F0F8FF 0%, #FFFFFF 50%, #FFFFFF 100%)"
                      height="288px"
                      title={otherQuestions.configName}
                      iconImg={HomeIcon2}
                      isToolBtn
                      isLoaded={isDataLoaded}
                    />
                  </motion.div>
                  <div>
                    <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>
  )
}
