'use client'

import {
  isChatButtleDrawerOpenAtom,
  isCrushLevelDrawerOpenAtom,
  createDrawerOpenState,
} from '@/atoms/chat'
import {
  InlineDrawer,
  InlineDrawerContent,
  InlineDrawerDescription,
  InlineDrawerFooter,
  InlineDrawerHeader,
} from './InlineDrawer'
import { useAtom, useSetAtom } from 'jotai'
import { Button } from '@/components/ui/button'
import { useGetChatBubbleDictList, useGetMyChatSetting, useSetChatBubble } from '@/hooks/useIm'
import { useChatConfig } from '../../context/chatConfig'
import { ChatBubbleListOutput, UnlockType } from '@/services/im/types'
import Image from 'next/image'
import { Tag } from '@/components/ui/tag'
import { useEffect, useState } from 'react'
import { useHeartLevelTextFromLevel } from '@/hooks/useHeartLevel'
import { cn } from '@/lib/utils'
import ChatBubble from '../ChatMessageItems/ChatBubble'
import { Checkbox } from '@/components/ui/checkbox'
import { useRouter } from 'next/navigation'
import { isVipDrawerOpenAtom } from '@/atoms/im'
import { useCurrentUser } from '@/hooks/auth'
import { VipType } from '@/services/wallet'
import { useQueryClient } from '@tanstack/react-query'
import { imKeys } from '@/lib/query-keys'

const ChatButtleItem = ({
  item,
  selected,
  inUse,
  onClick,
}: {
  item: ChatBubbleListOutput
  selected: boolean
  inUse: boolean
  onClick: () => void
}) => {
  return (
    <div className="cursor-pointer" onClick={onClick}>
      <div
        className={cn(
          'bg-surface-element-normal relative flex aspect-[41/30] items-center justify-center rounded-lg p-[2px]',
          selected && 'border-primary-normal border-2 border-solid p-0'
        )}
      >
        <ChatBubble isDefault={item.isDefault} img={item.webImgUrl}>
          Hi
        </ChatBubble>
        {inUse && <Checkbox checked={true} shape="round" className="absolute top-2 right-2" />}
        {item.isDefault && (
          <Tag className="absolute top-2 left-2" variant="dark" size="small">
            Default
          </Tag>
        )}
        {!item.isUnlock && (
          <Tag className="absolute top-2 right-2" variant="dark" size="small">
            <i className="iconfont icon-private-border" />
          </Tag>
        )}
      </div>
      {item.unlockType === 'MEMBER' ? (
        <div className="txt-label-m mt-2 bg-gradient-to-r from-[#ff9696] via-[#aa90f9] to-[#8df3e2] bg-clip-text text-center text-transparent">
          {item.name}
        </div>
      ) : (
        <div className="txt-label-m text-txt-primary-normal mt-2 text-center">{item.name}</div>
      )}
    </div>
  )
}

const ChatButtleDrawer = () => {
  const [selectedCode, setSelectedCode] = useState<string | undefined>()
  const [drawerState, setDrawerState] = useAtom(isChatButtleDrawerOpenAtom)
  const open = drawerState.open
  const setOpen = (open: boolean) => setDrawerState(createDrawerOpenState(open))
  const { aiId, aiInfo } = useChatConfig()
  const { chatBubble } = aiInfo || {}
  const setCrushLevelDrawerState = useSetAtom(isCrushLevelDrawerOpenAtom)
  const setIsCrushLevelDrawerOpen = (open: boolean) =>
    setCrushLevelDrawerState(createDrawerOpenState(open))
  const setIsVipDrawerOpen = useSetAtom(isVipDrawerOpenAtom)
  const queryClient = useQueryClient()

  const { data: chatBubbleDictList } = useGetChatBubbleDictList({ aiId })
  const { mutateAsync: setChatBubble, isPending: isSettingChatBubble } = useSetChatBubble({ aiId })

  useEffect(() => {
    if (!chatBubbleDictList?.length) return
    const defaultCode = chatBubble?.code?.toString()
    setSelectedCode(defaultCode || chatBubbleDictList[0]?.code?.toString())
  }, [chatBubbleDictList, chatBubble])

  useEffect(() => {
    if (open) {
      queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(aiId) })
      const defaultCode = chatBubble?.code?.toString()
      if (defaultCode) {
        setSelectedCode(defaultCode)
      }
    }
  }, [open])

  const handleSetChatBubble = async (code: string) => {
    await setChatBubble({ aiId, code })
    setOpen(false)
  }

  const renderConfirmButton = () => {
    if (!selectedCode) return
    const { isUnlock, unlockType, unlockHeartbeatLevel } =
      chatBubbleDictList?.find((item) => item.code === selectedCode) || {}
    if (isUnlock || isUnlock === null) {
      return (
        <Button
          size="large"
          loading={isSettingChatBubble}
          onClick={() => handleSetChatBubble(selectedCode)}
        >
          Confirm
        </Button>
      )
    }

    if (unlockType === UnlockType.Member) {
      return (
        <Button
          size="large"
          variant="vip"
          onClick={() => setIsVipDrawerOpen({ open: true, vipType: VipType.CUSTOM_CHAT_BUBBLE })}
        >
          <div className="flex items-center gap-2">
            <Image src="/icons/vip-black.svg" alt="vip" className="block" width={24} height={24} />
            <span className="txt-label-l">Unlock</span>
          </div>
        </Button>
      )
    }

    if (unlockType === UnlockType.HeartbeatLevel) {
      return (
        <Button size="large" onClick={() => setIsCrushLevelDrawerOpen(true)}>
          <div className="flex items-center gap-2">
            <Image
              src="/icons/like-gradient.svg"
              alt="vip"
              className="block"
              width={24}
              height={24}
            />
            <span className="txt-label-l">
              {useHeartLevelTextFromLevel(unlockHeartbeatLevel)} Unlock
            </span>
          </div>
        </Button>
      )
    }

    return null
  }

  return (
    <InlineDrawer
      id="chat-buttle-drawer"
      open={open}
      onOpenChange={setOpen}
      timestamp={drawerState.timestamp}
    >
      <InlineDrawerContent>
        <InlineDrawerHeader>Chat Buttles</InlineDrawerHeader>
        <InlineDrawerDescription>
          <div className="grid grid-cols-2 gap-4">
            {chatBubbleDictList?.map((item) => (
              <ChatButtleItem
                key={item.code}
                item={item}
                inUse={item.code === chatBubble?.code}
                selected={item.code === selectedCode}
                onClick={() => {
                  setSelectedCode(item.code)
                }}
              />
            ))}
          </div>
        </InlineDrawerDescription>
        <InlineDrawerFooter>
          <Button variant="tertiary" size="large" onClick={() => setOpen(false)}>
            Cancel
          </Button>
          {renderConfirmButton()}
        </InlineDrawerFooter>
      </InlineDrawerContent>
    </InlineDrawer>
  )
}

export default ChatButtleDrawer
