import { Button, Tooltip } from '@heroui/react'
import { useMemo, useRef, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useDebounceFn } from 'ahooks'
import type { Answer } from '@/types/chat'
import LikeIcon from '@/assets/svg/zan.svg?react'
import LikeIconA from '@/assets/svg/zanA.svg?react'
import UnLikeIcon from '@/assets/svg/cai.svg?react'
import UnLikeIconA from '@/assets/svg/caiA.svg?react'
import CopyIcon from '@/assets/svg/copy.svg?react'
import CollectIcon from '@/assets/svg/shouc.svg?react'
import CollectIconA from '@/assets/svg/shoucA.svg?react'
import useToast from '@/hooks/useToast'
import { fetchCancelCollection, fetchSubmitCollection, fetchSubmitFeedback } from '@/api/chat'
import { UnLikeModal } from '@/components/UnLikeModal'

interface ChatAnswerOperateProps {
  answer: Answer
}
export const ChatAnswerOperate: React.FC<ChatAnswerOperateProps> = ({ answer }) => {
  const showToast = useToast()
  const [searchParams] = useSearchParams()

  // 读取路由参数 from
  const from = searchParams.get('from')
  const fromValues = searchParams.getAll('from')

  // 兜底读取缓存的 tacticsMeta（会话从 tactics 打开的元信息）
  const tacticsMetaFromStorage = useMemo(() => {
    const raw = sessionStorage.getItem('tacticsMeta')
    if (!raw)
      return undefined
    try {
      return JSON.parse(raw)
    }
    catch {
      return undefined
    }
  }, [])

  // 兜底读取缓存的 userMeta（会话从用户视角打开的元信息）
  const userMetaFromStorage = useMemo(() => {
    const raw = sessionStorage.getItem('userMeta')
    if (!raw)
      return undefined
    try {
      return JSON.parse(raw)
    }
    catch {
      return undefined
    }
  }, [])

  // 检查路由参数中是否有 from=order
  const hasOrderFromRoute = fromValues.includes('order')

  // 规则：当 sessionStorage 中存在 userMeta 或 tacticsMeta 时，或路由参数 from=tactics 或 from=order 时，统一隐藏收藏按钮
  const shouldHideCollect = !!userMetaFromStorage || !!tacticsMetaFromStorage || from === 'tactics' || hasOrderFromRoute

  const [isCollect, setIsCollect] = useState(answer.collectionFlag)
  const [isLike, setIsLike] = useState(answer.feedbackStatus === '01')
  const [isUnLike, setIsUnLike] = useState(answer.feedbackStatus === '02')
  const [isOpenUnLikeModal, setIsOpenUnLikeOpen] = useState(false)
  const isProcessingRef = useRef(false)

  const handleCollect = useDebounceFn(async () => {
    // 防止重复调用
    if (isProcessingRef.current) {
      return
    }

    isProcessingRef.current = true

    try {
      if (!isCollect) {
        setIsCollect(true)
        const res = await fetchSubmitCollection(answer.recordId || '')
        if (res.ok) {
          showToast('收藏成功！', 'success')
        }
 else {
          // 如果请求失败，回滚状态
          setIsCollect(false)
        }
      }
      else {
        setIsCollect(false)
        const res = await fetchCancelCollection(answer.recordId || '')
        if (!res.ok) {
          // 如果请求失败，回滚状态
          setIsCollect(true)
        }
      }
    }
 finally {
      isProcessingRef.current = false
    }
  }, { wait: 200 })

  const handleLike = useDebounceFn(async () => {
    if (!isLike) {
      setIsLike(true)
      setIsUnLike(false)
      await fetchSubmitFeedback({
        recordId: answer.recordId,
        feedbackStatus: '01',
        content: '',
      })
      showToast('感谢您的反馈', 'success')
    }
    else {
      setIsLike(false)
      await fetchSubmitFeedback({
        recordId: answer.recordId,
        feedbackStatus: '00',
        content: '',
      })
    }
  })

  const handleUnLike = async () => {
    if (!isUnLike) {
      setIsOpenUnLikeOpen(true)
    }
    else {
      setIsUnLike(false)
      await fetchSubmitFeedback({
        recordId: answer.recordId,
        feedbackStatus: '00',
        content: '',
      })
    }
  }

  const handleClose = (isSubmit?: boolean) => {
    setIsOpenUnLikeOpen(false)
    if (isSubmit) {
      setIsLike(false)
      setIsUnLike(true)
      showToast('感谢您的反馈', 'success')
    }
  }

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(answer.answer)
      showToast('复制成功！', 'success')
    }
    catch {
      // 如果 clipboard API 不可用，使用传统方法
      const textArea = document.createElement('textarea')
      textArea.value = answer.answer
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      showToast('复制成功！', 'success')
    }
  }
  return (
    <div className="sm:mt-[12px] flex gap-[4px] justify-end">
      {/* 点赞 / 点踩 / 复制：默认始终展示 */}
      {/* 点赞 */}
      <Tooltip color="foreground" content={isLike ? '取消点赞' : '点赞'} className="capitalize">
        <Button variant="light" isIconOnly aria-label="LikeIcon" onPress={handleLike.run}>
          {isLike ? <LikeIconA /> : <LikeIcon />}
        </Button>
      </Tooltip>
      {/* 点踩 */}
      <Tooltip color="foreground" content={isUnLike ? '取消点踩' : '点踩'} className="capitalize">
        <Button variant="light" isIconOnly aria-label="UnLikeIcon" onPress={handleUnLike}>
          {isUnLike ? <UnLikeIconA /> : <UnLikeIcon />}
        </Button>
      </Tooltip>
      {/* 复制 */}
      <Tooltip color="foreground" content="复制" className="capitalize">
        <Button variant="light" isIconOnly aria-label="CopyIcon" onPress={handleCopy}>
          <CopyIcon />
        </Button>
      </Tooltip>
      {/* 收藏（当路由未标记 from=tactics 且不存在 userMeta 缓存时才展示） */}
      {!shouldHideCollect && (
        <Tooltip color="foreground" content={isCollect ? '取消收藏' : '收藏'} className="capitalize">
          <Button variant="light" isIconOnly aria-label="CollectIcon" onPress={handleCollect.run}>
            {isCollect ? <CollectIconA /> : <CollectIcon />}
          </Button>
        </Tooltip>
      )}
      {/* 重新生成 */}
      {/* <Tooltip color="foreground" content="重新生成" className="capitalize">
        <Button variant="light" isIconOnly aria-label="ReloadIcon"><ReloadIcon /></Button>
      </Tooltip> */}

      <UnLikeModal answer={answer} isOpen={isOpenUnLikeModal} onClose={handleClose} />
    </div>
  )
}
