'use client'

import { Button, IconButton } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { useGetAIUserBaseInfo, useGetAIUserStat } from '@/hooks/aiUser'
import { useParams, useRouter } from 'next/navigation'
import { formatNumberToKMB, getAge } from '@/lib/utils'
import { Tag } from '@/components/ui/tag'
import Image from 'next/image'
import { useAIUser } from '../context/aiUser'
import { useEditFormStorage, useEditAI, useEditAIAvatar } from '@/hooks/create'
import { useNimChat, useNimConversation } from '@/context/NimChat/useNimChat'
import { useCurrentUser, useToken } from '@/hooks/auth'
import { AvatarCropModal } from '@/components/ui/avatar-crop-modal'
import { useState, useRef } from 'react'
import { BizTypeEnum } from '@/services/common'
import { AIPermission, CreateOrEditAiRequest } from '@/services/create'
import UserShare from './UserShare'
import UserLikeButton from './UserLikeButton'
import Decimal from 'decimal.js'

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

export function UserCard() {
  const { userId } = useParams()
  const { data } = useGetAIUserBaseInfo({ aiId: Number(userId) })
  const { isOwner } = useAIUser()
  const router = useRouter()
  const { insertConversationActive } = useNimConversation()

  const { birthday, characterName, headImg, nickname, sex, tagName, homeImageUrl } = data || {}
  const { data: statData } = useGetAIUserStat({ aiId: Number(userId) })
  const { chatNum, coinNum, conversationNum, likedNum } = statData || {}
  const { clearFormData } = useEditFormStorage()
  const { isNimLoggedIn } = useNimChat()
  const { getLoginStatus } = useToken()

  // AI用户编辑hook
  const { mutateAsync: editAIAvatar, isPending: isEditingAIAvatar } = useEditAIAvatar()

  // 头像裁剪相关状态
  const [showCropModal, setShowCropModal] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const statList = [
    {
      label: 'Likes',
      value: formatNumberToKMB(likedNum || 0),
    },
    {
      label: 'Chats',
      value: formatNumberToKMB(chatNum || 0),
    },
    {
      label: 'Users',
      value: formatNumberToKMB(conversationNum || 0),
    },
    isOwner && {
      label: 'CrushCoin',
      value: formatNumberToKMB(new Decimal(coinNum || 0).div(100).toNumber()),
    },
  ].filter(Boolean) as { label: string; value: string | number }[]

  const handleEdit = () => {
    clearFormData()
    router.push(`/edit/${userId}/type`)
  }

  const handleChat = () => {
    if (!getLoginStatus()) {
      router.push(`/chat/${userId}`)
      return
    }

    if (!isNimLoggedIn) {
      return
    }
    // insertConversationActive({
    //   receiverId: `${userId}@r@t` as string,
    // })
    router.push(`/chat/${userId}`)
  }

  // 处理头像点击
  const handleAvatarClick = () => {
    if (!isOwner) return
    setShowCropModal(true)
  }

  // 处理裁剪完成
  const handleCropComplete = async (croppedImageUrl: string) => {
    try {
      // 更新AI用户头像 - 只更新头像，其他信息保持原样
      await editAIAvatar({
        aiId: Number(userId),
        userHead: croppedImageUrl,
      })
    } catch (error) {
      // 可以添加错误提示
    } finally {
      setShowCropModal(false)
      // 清空文件输入
      if (fileInputRef.current) {
        fileInputRef.current.value = ''
      }
    }
  }

  // 处理裁剪取消
  const handleCropCancel = () => {
    setShowCropModal(false)
    // 清空文件输入
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  const renderChatButton = () => {
    if (isOwner) {
      return (
        <Button variant="tertiary" size="large" className="flex-1" onClick={handleEdit}>
          Edit
        </Button>
      )
    }

    return (
      <Button size="large" className="flex-1" onClick={handleChat}>
        Chat
      </Button>
    )
  }

  if (!data) {
    return null
  }

  return (
    <div className="relative">
      {/* 背景卡片 */}
      <div className="absolute top-16 right-0 bottom-0 left-0 rounded-2xl bg-[#352e3e]" />

      {/* 内容 */}
      <div className="relative flex flex-col items-center justify-start gap-6 px-6 pt-0 pb-6">
        {/* 头像 */}
        <div className="relative size-32">
          <Avatar
            className={`size-full ${isOwner ? 'cursor-pointer transition-opacity hover:opacity-80' : ''}`}
            onClick={handleAvatarClick}
          >
            <AvatarImage src={headImg} width={128} height={128} className="object-cover" />
            <AvatarFallback className="!txt-headline-l text-txt-primary-normal">
              {nickname?.slice(0, 1)}
            </AvatarFallback>
          </Avatar>
        </div>

        {/* 用户信息 */}
        <div className="flex w-full flex-col items-start justify-start gap-4">
          {/* 用户名 */}
          <h1 className="txt-headline-s w-full truncate text-center">{nickname}</h1>

          {/* 标签 */}
          <div className="flex w-full flex-wrap items-start justify-center gap-2">
            {/* 年龄和性别标签 */}
            <Tag>
              <Image src={genderMap[sex ?? 0]} alt="Gender" width={16} height={16} />
              <div>{getAge(birthday ?? 0)}</div>
            </Tag>
            <Tag>{characterName}</Tag>
            <Tag>{tagName}</Tag>
          </div>
        </div>

        {/* 统计数据 */}
        <div className="bg-surface-nest-normal flex w-full flex-row items-start justify-start rounded-sm px-1 py-3">
          {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>

        {/* 操作按钮 */}
        <div className="flex w-full flex-row items-start justify-center gap-4">
          {/* 分享按钮 */}
          <UserShare />

          {/* 聊天 */}
          {isOwner && (
            <IconButton variant="tertiary" size="large" onClick={handleChat}>
              <i className="iconfont icon-Chat" />
            </IconButton>
          )}

          <UserLikeButton />

          {renderChatButton()}
        </div>
      </div>

      {/* 头像裁剪弹窗 */}
      {homeImageUrl && (
        <AvatarCropModal
          isOpen={showCropModal}
          onClose={() => setShowCropModal(false)}
          image={homeImageUrl}
          onConfirm={handleCropComplete}
          onCancel={handleCropCancel}
          bizType={BizTypeEnum.Album}
        />
      )}
    </div>
  )
}
