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 HomeIcon1 from '@/assets/homeIcon1.png'
import HomeIcon2 from '@/assets/homeIcon2.png'
import { createConversation, fetchConversations } from '@/store/conversationSlice'
import { useAppDispatch } from '@/store/hook'
import { fetchQuestionList } from '@/api/home'
import SdreamLoading from '@/components/SdreamLoading'
// import { fetchLoginByToken } from '@/api/common'
import { 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 [isLoading, setIsLoading] = useState(false)
  const dispatch = useAppDispatch()
  const location = useLocation()
  const hasFetched = useRef(false)
  // 使用 useState
  const [productQuestions, setProductQuestions] = useState<any>({ content: [] })
  const [otherQuestions, setOtherQuestions] = useState<any>({ content: [] })

  const [token, setToken] = useLocalStorageState<string | undefined>('__TOKEN__', {
    defaultValue: '',
  })
  // 检查当前路径是否包含 "/chat/"
  // const showOutlet = location.pathname.includes('/chat/')
  // const handleCreateConversation = (question: string) => {
  //   dispatch(
  //     createConversation({
  //       conversationData: {},
  //       shouldNavigate: true,
  //       shouldSendQuestion: question,
  //       }),
  //   )
  // }

  /** 获取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 === '06') {
            element.content = JSON.parse(element.content)
            setProductQuestions(element)
          }
          if (element.configType === '07') {
            element.content = JSON.parse(element.content)
            setOtherQuestions(element)
          }
        }
      }
    }
    catch (error) {
      // 可以在这里添加错误处理逻辑
      console.error('Failed to fetch chat records:', error)
    }
    finally {
      setIsLoading(false)
    }
  }, [])

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

    // const res = await fetchLoginByToken(loginCode)
    // 模拟登录 可以用来测试
    const 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(() => {
    if (!token) {
      login()
    }
    else {
      getQuestionList()
      initConversation()
      dispatch(fetchConversations())
    }
  }, [token])

  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]  overflow-y-scroll sm:pt-[32px] scrollbar-hide sm:overflow-hidden">
            <div className="w-full">
              <div className="flex justify-center gap-[20px] mt-[22px] sm:mt-[62px]">
                {/* 左侧区域 - 产品问答和您可以试着问我 */}
                <div className="flex flex-col gap-[20px] sm:mt-[-62px] justify-center">
                  <motion.div className="w-full hidden sm:block sm:w-auto" {...getAnimationProps(2)}>
                    <QuestionList
                      questions={productQuestions.content}
                      dotColor="#D4CCFF"
                      background="linear-gradient( 180deg, #EBE6FF 0%, #FFFFFF 100%)"
                      title={productQuestions.configName}
                      iconImg={HomeIcon1}
                    />
                  </motion.div>
                  <motion.div className="w-full sm:w-auto" {...getAnimationProps(3)}>
                    <QuestionList
                      questions={otherQuestions.content}
                      dotColor="#CBECFF"
                      background="linear-gradient( 180deg, #DBF1FF 0%, #FFFFFF 100%)"
                      title={otherQuestions.configName}
                      iconImg={HomeIcon2}
                    />
                  </motion.div>
                </div>
                {/* 右侧区域 */}
                <div className="hidden sm:flex flex-1 h-full sm:mt-[-62px]">
                  <div
                    className="w-full h-full bg-transparent box-border rounded-[24px]"
                    style={{ height: 'calc(100vh - 64px)', background: '#FFFFFF', padding: '0 30px' }}
                  >
                    <Outlet />
                    {/* {showOutlet
                      ? (
                          <Outlet />
                        )
                      : (
                          <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: '100%' }}>
                            <Slogan />
                            <div className="box-border px-[0] mx-auto iptContainer w-full flex-shrink-0 sm:px-0 pb-[18px]">
                              <ChatEditor
                                showContentTips
                                onSubmit={handleCreateConversation}
                                placeholders={RECOMMEND_QUESTIONS_OTHER}
                              />
                              <div className="hidden sm:block w-full text-center mt-[12px] text-[#3333334d] text-[12px]">
                                内容由AI模型生成，其准确性和完整性无法保证，仅供参考
                              </div>
                            </div>
                          </div>
                        )} */}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
