import { useEffect, useRef, useState } from 'react'
import { Button, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Tooltip } from '@heroui/react'
import { motion } from 'framer-motion'
import { useNavigate } from 'react-router-dom'
import { formatMarkdown } from '../Chat/components/ChatItem/markdownFormatter'
import { ChatAnswerAttachment } from '../Chat/components/ChatItem/ChatAnswerAttchment'
import styles from './Collect.module.less'
import { fetchQueryCollectionList } from '@/api/collect'
import DeleteIcon from '@/assets/svg/delete.svg?react'
import { fetchDelCollection } from '@/api/chat'
import { MarkdownDetail } from '@/components/MarkdownDetail'
import AIcon from '@/assets/svg/aicon.svg?react'
import QIcon from '@/assets/svg/qicon.svg?react'
import EmptyIcon from '@/assets/svg/empty.svg?react'
import ShineBorder from '@/components/ShineBorder'
import SdreamLoading from '@/components/SdreamLoading'

export const Collect: React.FC = () => {
  const navigate = useNavigate()
  const hasLoaded = useRef(false)

  const [isLoading, setIsLoading] = useState(false)
  const [isOpen, setIsOpen] = useState(false)
  const [collectList, setCollectList] = useState<any>([])
  const [curCollectId, setCollectId] = useState('')
  const [pageNum, setPageNum] = useState(1)
  const [pageSize] = useState(5)
  const [total, setTotal] = useState(0)

  const getCollectList = async () => {
    // 防止重复调用
    if (hasLoaded.current) {
      return
    }

    hasLoaded.current = true

    setIsLoading(true)
    const params = {
      pageNum,
      pageSize,
    }
    try {
      const res = await fetchQueryCollectionList(params)
      // 使用函数式更新确保获取最新的 collectList 值
      setCollectList((prevList: any) => [...prevList, ...res.data.records])
      setTotal(res.data.total)
    }
 catch (error) {
      console.error('获取收藏列表失败:', error)
      hasLoaded.current = false // 出错时重置标志位
    }
 finally {
      setIsLoading(false)
    }
  }

  const handleDelete = (item: any) => {
    setIsOpen(true)
    setCollectId(item.collectionId)
  }

  const handleSureDel = async () => {
    const idx = collectList.findIndex((item: any) => item.collectionId === curCollectId)
    const res = await fetchDelCollection([curCollectId])
    setIsOpen(false)
    if (res.ok) {
      if (collectList.length < pageSize) {
        const resList = await fetchQueryCollectionList({ pageNum: 1, pageSize })
        setCollectList(resList.data.records)
        setTotal(resList.data.total)
      }
      else {
        const _collectList = JSON.parse(JSON.stringify(collectList))
        _collectList.splice(idx, 1)
        setCollectList(_collectList)
        setTotal(total - 1)
      }
    }
  }

  const handleLoadMore = () => {
    setPageNum(pageNum + 1)
  }

  // 添加返回上一页的函数
  const handleGoBack = () => {
    // 设置标记，用于 Chat 组件检测从收藏页返回
    sessionStorage.setItem('fromCollect', 'true')
    if (window.history.length > 1) {
      navigate(-1)
      return
    }
    const conversationId = sessionStorage.getItem('currentConversationId') || ''
    navigate(`/chat/${conversationId}`, { state: { fromCollect: true } })
  }

  useEffect(() => {
    getCollectList()
    // 清理函数，在组件卸载时重置标志位
    return () => {
      hasLoaded.current = false
    }
  }, [])
  return (
    <div className={styles.scrollView}>
      <div className={`${styles.collectPage} relative`}>
        {/* <ChatSlogan />
        <ChatMaskBar /> */}
        <div className="content h-full overflow-y-auto pt-[24px]">
          <div onClick={handleGoBack} className="flex items-center cursor-pointer text-blue-500 hover:text-blue-700 transition-colors duration-200">
            <svg
              className="w-5 h-5 mr-1"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M19 12H5M12 19L5 12L12 5"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
            <span className="font-medium">返回</span>
          </div>
          <motion.div className={`${styles.collectScrollable} scrollbar-hide`}>
            <div className={`${styles.inter}`}>
              {collectList.length !== 0 && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{
                    duration: 0.3,
                    opacity: { duration: 0.1 },
                  }}
                  className="flex flex-col gap-[24px]"
                >
                  {collectList.map((item: any, index: number) => (
                    <ShineBorder
                      borderRadius={20}
                      className="text-[#27353C] w-full mx-auto bg-white rounded-[20px] box-border px-[24px] py-[20px]"
                      key={`${item.collectionId}_${index}`}
                    >
                      <div className="flex mb-[20px]">
                        <div className="mr-[20px]">
                          <QIcon />
                        </div>
                        <div className="font-bold text-[16px]">{item.question}</div>
                      </div>
                      <div className="flex">
                        <div className="mr-[20px]">
                          <AIcon />
                        </div>
                        <div className="flex-1">
                          <MarkdownDetail>{formatMarkdown(item.answer || '')}</MarkdownDetail>
                          {item.cardList && item.cardList?.length !== 0 && <ChatAnswerAttachment answer={item} isAsking={false} />}
                          <div className="mt-[12px] flex gap-[4px] justify-between items-center">
                            <div className="text-12px text-[#B2B8C1]">{item.collectionTime}</div>
                            <div>
                              <Tooltip color="foreground" content="删除" className="capitalize">
                                <Button
                                  variant="light"
                                  isIconOnly
                                  aria-label="DeleteIcon"
                                  onPress={() => handleDelete(item)}
                                >
                                  <DeleteIcon />
                                </Button>
                              </Tooltip>
                            </div>
                          </div>
                        </div>
                      </div>
                    </ShineBorder>
                  ))}
                </motion.div>
              )}
              {collectList.length === 0 && !isLoading && (
                <div className="flex w-full h-full items-center justify-center flex-col">
                  <EmptyIcon />
                  <p className="text-[13px] text-[#27353C] mt-[16px]">暂无收藏记录</p>
                </div>
              )}
              {isLoading && (
                <div className="w-full flex justify-center items-center">
                  <SdreamLoading />
                </div>
              )}
              {!isLoading && collectList.length < total && (
                <div className="w-full mx-auto flex justify-center mt-[24px]">
                  <Button onPress={handleLoadMore} color="primary" variant="light">
                    加载更多
                  </Button>
                </div>
              )}
              {collectList.length === total && collectList.length !== 0 && (
                <div className="w-full mt-[24px] mx-auto flex justify-center text-[#8D9795]">到底啦~</div>
              )}
            </div>
          </motion.div>
        </div>
      </div>

      <Modal backdrop="blur" isOpen={isOpen} onClose={() => setIsOpen(false)}>
        <ModalContent>
          {onClose => (
            <>
              <ModalHeader className="flex flex-col gap-1">删除提示</ModalHeader>
              <ModalBody className="text-[#27353C]">
                确认删除当前收藏内容吗？删除后，此条收藏的内容将不可恢复。
              </ModalBody>
              <ModalFooter>
                <Button onPress={onClose}>再想想</Button>
                <Button color="primary" onPress={handleSureDel}>
                  确认
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  )
}
