import { InlineDrawer, InlineDrawerContent } from '../InlineDrawer'
import { useAtom, useSetAtom } from 'jotai'
import {
  isChatBackgroundDrawerOpenAtom,
  isChatProfileDrawerOpenAtom,
  createDrawerOpenState,
} from '@/atoms/chat'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { Tag } from '@/components/ui/tag'
import { Switch } from '@/components/ui/switch'
import { useEffect, useState } from 'react'
import ChatProfileAction from './ChatProfileAction'
import { useChatConfig } from '../../../context/chatConfig'
import Image from 'next/image'
import { formatNumberToKMB, getAge } from '@/lib/utils'
import { useGetAIUserStat } from '@/hooks/aiUser'
import { IconButton } from '@/components/ui/button'
import { useGetMyChatSetting, useSetAutoPlayVoice } from '@/hooks/useIm'
import ChatProfilePersona from './ChatProfilePersona'
import { isChatButtleDrawerOpenAtom, isChatModelDrawerOpenAtom } from '@/atoms/chat'
import { Badge } from '@/components/ui/badge'
import { useRedDot, RED_DOT_KEYS } from '@/hooks/useRedDot'
import { imKeys } from '@/lib/query-keys'
import { AiUserImBaseInfoOutput } from '@/services/im'
import { useQueryClient } from '@tanstack/react-query'
import CrushLevelAvatar from '../../CrushLevelAvatar'
import ChatProfileLikeAction from './ChatProfileLikeAction'
import { isVipDrawerOpenAtom } from '@/atoms/im'
import { useCurrentUser } from '@/hooks/auth'
import { VipType } from '@/services/wallet'
import Decimal from 'decimal.js'

const genderMap = {
  0: '/icons/male.svg',
  1: '/icons/female.svg',
  2: '/icons/gender-neutral.svg',
}

const ChatProfileDrawer = () => {
  const [drawerState, setDrawerState] = useAtom(isChatProfileDrawerOpenAtom)
  const isChatProfileDrawerOpen = drawerState.open
  const setIsChatProfileDrawerOpen = (open: boolean) => setDrawerState(createDrawerOpenState(open))

  const setModelDrawerState = useSetAtom(isChatModelDrawerOpenAtom)
  const setIsChatModelDrawerOpen = (open: boolean) =>
    setModelDrawerState(createDrawerOpenState(open))

  const setButtleDrawerState = useSetAtom(isChatButtleDrawerOpenAtom)
  const setIsChatButtleDrawerOpen = (open: boolean) =>
    setButtleDrawerState(createDrawerOpenState(open))

  const setBackgroundDrawerState = useSetAtom(isChatBackgroundDrawerOpenAtom)
  const setIsChatBackgroundDrawerOpen = (open: boolean) =>
    setBackgroundDrawerState(createDrawerOpenState(open))
  const setIsVipDrawerOpen = useSetAtom(isVipDrawerOpenAtom)

  const { aiId, aiInfo } = useChatConfig()
  const { data: user } = useCurrentUser() || {}
  const { isMember } = user || {}

  const isOwner = user?.userId === aiInfo?.userId

  // 使用红点管理hooks
  const { hasRedDot, markAsViewed } = useRedDot()

  const { data: statData } = useGetAIUserStat({ aiId })
  const {
    sex,
    birthday,
    characterName,
    tagName,
    chatBubble,
    isDefaultBackground,
    isAutoPlayVoice,
    aiUserHeartbeatRelation,
  } = aiInfo || {}
  const { likedNum, chatNum, conversationNum, coinNum } = statData || {}
  const { heartbeatLevel } = aiUserHeartbeatRelation || {}

  const { mutate: setAutoPlayVoice } = useSetAutoPlayVoice()
  const queryClient = useQueryClient()

  useEffect(() => {
    if (isChatProfileDrawerOpen) {
      queryClient.invalidateQueries({ queryKey: imKeys.imUserInfo(aiId) })
    }
  }, [isChatProfileDrawerOpen])

  const statList = [
    {
      label: 'Liked',
      value: formatNumberToKMB(likedNum || 0),
    },
    {
      label: 'Chat',
      value: formatNumberToKMB(chatNum || 0),
    },
    {
      label: 'People',
      value: formatNumberToKMB(conversationNum || 0),
    },
    isOwner && {
      label: 'Crush Coin',
      value: formatNumberToKMB(new Decimal(coinNum || 0).div(100).toNumber()),
    },
  ].filter(Boolean) as { label: string; value: string | number }[]

  const handleClose = () => {
    setIsChatProfileDrawerOpen(false)
  }

  return (
    <InlineDrawer
      id="chatProfile"
      open={isChatProfileDrawerOpen}
      onOpenChange={setIsChatProfileDrawerOpen}
      timestamp={drawerState.timestamp}
    >
      <InlineDrawerContent>
        {/* <div className="absolute top-0 left-0 right-0 h-[228px]" style={{ background: "linear-gradient(0deg, rgba(194, 65, 230, 0) 0%, #F264A4 100%)" }} /> */}
        <div className="relative h-full w-full">
          {/* Header with back and more buttons */}
          <ChatProfileAction />
          <IconButton
            iconfont="icon-arrow-right"
            variant="ghost"
            size="small"
            className="absolute top-6 left-6"
            onClick={handleClose}
          />

          <div className="h-full w-full overflow-y-auto">
            <div
              className="flex flex-col items-center justify-start gap-6 px-6 pt-12 pb-10"
              style={{
                background: heartbeatLevel
                  ? 'linear-gradient(0deg, rgba(194, 65, 230, 0) 0%, #F264A4 100%)'
                  : undefined,
                backgroundSize: '100% 228px',
                backgroundRepeat: 'no-repeat',
              }}
            >
              <CrushLevelAvatar showText />

              {/* Name and Tags */}
              <div className="flex w-full flex-col items-start justify-start gap-4">
                <div className="flex w-full flex-wrap items-start justify-center gap-2">
                  <Tag>
                    <Image
                      src={genderMap[sex as keyof typeof genderMap]}
                      alt="Gender"
                      width={16}
                      height={16}
                    />
                    <div>{getAge(Number(birthday))}</div>
                  </Tag>
                  <Tag>{characterName}</Tag>
                  <Tag>{tagName}</Tag>
                </div>
              </div>

              <ChatProfileLikeAction />

              {/* Statistics */}
              <div className="flex w-full flex-row items-start justify-start px-1 py-0">
                {statList.map((item, index) => (
                  <div
                    key={index}
                    className="flex flex-1 flex-col items-center justify-start gap-1 px-1 py-0"
                  >
                    <div className="txt-numDisplay-s text-txt-primary-normal">{item.value}</div>
                    <div className="txt-label-s text-txt-secondary-normal">{item.label}</div>
                  </div>
                ))}
              </div>

              <ChatProfilePersona />

              {/* Chat Setting */}
              <div className="flex w-full flex-col items-start justify-start gap-3">
                <div className="txt-title-s w-full text-left">Chat Setting</div>
                <div className="flex w-full flex-col items-start justify-start gap-4">
                  <div
                    className="bg-surface-base-normal rounded-m flex w-full cursor-pointer items-center justify-between px-4 py-3"
                    onClick={() => {
                      setIsChatModelDrawerOpen(true)
                    }}
                  >
                    <div className="txt-label-l flex-shrink-0">Chat Model</div>
                    <div className="flex min-w-0 flex-1 cursor-pointer items-center justify-end gap-2">
                      <div className="txt-body-l text-txt-primary-normal text-right">
                        Role-Playing
                      </div>
                      <IconButton iconfont="icon-arrow-right-border" size="small" variant="ghost" />
                    </div>
                  </div>

                  <div className="bg-surface-base-normal rounded-m w-full py-1">
                    <div
                      className="flex w-full cursor-pointer items-center justify-between px-4 py-3"
                      onClick={() => {
                        markAsViewed(RED_DOT_KEYS.CHAT_BUBBLE)
                        setIsChatButtleDrawerOpen(true)
                      }}
                    >
                      <div className="txt-label-l flex-1">
                        <div className="flex flex-row items-center gap-2">
                          <div>Chat Bubble</div>
                          {hasRedDot(RED_DOT_KEYS.CHAT_BUBBLE) && <Badge variant="dot" />}
                        </div>
                      </div>
                      <div className="flex min-w-0 flex-1 cursor-pointer items-center justify-end gap-2">
                        {/* <div className="txt-body-l text-txt-primary-normal truncate">{chatBubble?.name || 'Default'}</div> */}
                        <IconButton
                          iconfont="icon-arrow-right-border"
                          size="small"
                          variant="ghost"
                        />
                      </div>
                    </div>

                    <div
                      className="flex w-full cursor-pointer items-center justify-between px-4 py-3"
                      onClick={() => {
                        markAsViewed(RED_DOT_KEYS.CHAT_BACKGROUND)
                        setIsChatBackgroundDrawerOpen(true)
                      }}
                    >
                      <div className="txt-label-l flex-1">
                        <div className="flex flex-row items-center gap-2">
                          <div>Chat Background</div>
                          {hasRedDot(RED_DOT_KEYS.CHAT_BACKGROUND) && <Badge variant="dot" />}
                        </div>
                      </div>
                      <div className="flex min-w-0 flex-1 cursor-pointer items-center justify-end gap-2">
                        {/* <div className="txt-body-l text-txt-primary-normal truncate">{isDefaultBackground ? 'Default' : ''}</div> */}
                        <IconButton
                          iconfont="icon-arrow-right-border"
                          size="small"
                          variant="ghost"
                        />
                      </div>
                    </div>
                  </div>

                  <div
                    className="bg-surface-base-normal rounded-m flex w-full cursor-pointer items-center justify-between px-4 py-3"
                    onClick={() => {
                      const checked = !isAutoPlayVoice
                      if (!isMember) {
                        setIsVipDrawerOpen({ open: true, vipType: VipType.AUTO_PLAY_VOICE })
                        return
                      }
                      queryClient.setQueryData(
                        imKeys.imUserInfo(aiId),
                        (oldData: AiUserImBaseInfoOutput) => {
                          return {
                            ...oldData,
                            isAutoPlayVoice: checked,
                          }
                        }
                      )
                      setAutoPlayVoice({ aiId, isAutoPlayVoice: checked })
                    }}
                  >
                    <div className="txt-label-l flex-1">Auto play voice</div>
                    <div className="flex h-8 items-center">
                      <Switch size="sm" checked={!!isAutoPlayVoice} />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </InlineDrawerContent>
    </InlineDrawer>
  )
}

export default ChatProfileDrawer
