import { useEffect, useState } from 'react'
import { Button, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Tooltip } from '@nextui-org/react'
import { motion } from 'framer-motion'
import { ChatMaskBar } from '../Chat/components/ChatMaskBar'
import { ChatSlogan } from '../Chat/components/ChatSlogan'
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 CopyIcon from '@/assets/svg/copy.svg?react'
import DeleteIcon from '@/assets/svg/delete.svg?react'
import type { Answer } from '@/types/chat'
import useToast from '@/hooks/useToast'
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 [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 showToast = useToast()

  const getCollectList = async () => {
    setIsLoading(true)
    const params = {
      pageNum,
      pageSize,
    }
    const res = await fetchQueryCollectionList(params)
    let timer = null as any
    timer = setTimeout(() => {
      setCollectList([...collectList, ...res.data.records])
      setTotal(res.data.total)
      setIsLoading(false)
      clearTimeout(timer)
      timer = null
    }, 500)
  }

  const handleCopy = async (item: Answer) => {
    if (!navigator.clipboard) {
      showToast('您的浏览器不支持复制', 'error')
      return
    }
    const text = `问：${item.question}\n答：${item.answer}
    `
    await navigator.clipboard.writeText(text)

    showToast('复制成功！快去分享吧！', 'success')
  }

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

  useEffect(() => {
    getCollectList()
  }, [pageNum])
  return (
    <div className={styles.scrollView}>
      <div className={`${styles.collectPage} relative`}>
        <ChatSlogan />
        <ChatMaskBar />
        <div className="content h-full overflow-y-auto">
          <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 max-w-[912px] 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} />}
                              <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="CopyIcon" onClick={() => handleCopy(item)}><CopyIcon /></Button>
                                  </Tooltip>
                                  <Tooltip color="foreground" content="删除" className="capitalize">
                                    <Button variant="light" isIconOnly aria-label="DeleteIcon" onClick={() => 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 max-w-[912px] mx-auto flex justify-center mt-[24px]">
                    <Button onClick={handleLoadMore} color="primary" variant="light">
                      加载更多
                    </Button>
                  </div>
                )
              }
              {
                collectList.length === total && collectList.length !== 0 && (
                  <div className="w-full mt-[24px] max-w-[912px] 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>
  )
}
