import { useGetAIUserBaseInfo } from '@/hooks/aiUser'
import { cn, loadImageAsync } from '@/lib/utils'
import { useParams } from 'next/navigation'
import { useEffect, useRef, useState } from 'react'

const getDominantColor = (data: Uint8ClampedArray) => {
  let red = 0,
    green = 0,
    blue = 0
  const length = data.length
  for (let i = 0; i < length; i += 4) {
    red += data[i]
    green += data[i + 1]
    blue += data[i + 2]
  }
  // 计算像素点数
  const pixelCount = length / 4
  red = Math.round(red / pixelCount)
  green = Math.round(green / pixelCount)
  blue = Math.round(blue / pixelCount)
  return `${red}, ${green}, ${blue}`
}

const getImageRightDominantColor = (ctx: any, image: any) => {
  const imageData = ctx.getImageData(image.width - 1, 0, 1, image.height)
  return getDominantColor(imageData.data)
}
const getImageLeftDominantColor = (ctx: any, image: any) => {
  const imageData = ctx.getImageData(0, 0, 1, image.height)
  return getDominantColor(imageData.data)
}

const UserBackground = () => {
  const { userId } = useParams()
  const { data } = useGetAIUserBaseInfo({ aiId: Number(userId) })
  const [colors, setColors] = useState({
    leftColor: '#37363b',
    rightColor: '#313133',
  })
  const [isLoading, setIsLoading] = useState(true)
  const canvasRef = useRef<HTMLCanvasElement>(null)

  // 获取图片两边的颜色
  const getImageColors = async (url: string) => {
    const image: any = await loadImageAsync(url)
    const canvas: any = canvasRef.current
    canvas.width = image.width
    canvas.height = image.height
    const ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0)
    const rightColor = getImageRightDominantColor(ctx, image)
    const leftColor = getImageLeftDominantColor(ctx, image)
    return {
      leftColor,
      rightColor,
    }
  }

  useEffect(() => {
    const init = async () => {
      if (data?.homeImageUrl) {
        setIsLoading(true)
        try {
          const { leftColor, rightColor } = await getImageColors(data.homeImageUrl)
          setColors({
            leftColor,
            rightColor,
          })
        } catch (error) {
          console.error('获取图片颜色失败:', error)
        } finally {
          setIsLoading(false)
        }
      } else {
        setIsLoading(false)
      }
    }
    init()
  }, [data?.homeImageUrl])

  if (!data) {
    return null
  }

  return (
    <>
      {/* 背景头部区域 */}
      <div className="bg-background-default absolute top-0 right-0 left-0 h-60 overflow-hidden">
        {/* 加载状态 - 显示默认背景 */}
        {isLoading && (
          <>
            <div className="absolute top-0 right-1/2 left-0 h-60 bg-[#36363b]" />
            <div className="absolute top-0 right-0 left-1/2 h-60 bg-[#313133]" />
          </>
        )}

        {/* 加载完成后的背景 */}
        {!isLoading && (
          <>
            <div
              className="absolute top-0 right-1/2 left-0 h-60 bg-[#36363b] transition-all duration-500 ease-in-out"
              style={{ background: `rgb(${colors.leftColor})` }}
            />
            <div
              className="absolute top-0 right-0 left-1/2 h-60 bg-[#313133] transition-all duration-500 ease-in-out"
              style={{ background: `rgb(${colors.rightColor})` }}
            />

            {/* 背景图片 */}
            <div
              className="absolute top-[-167px] left-1/2 h-[1337px] w-[752px] translate-x-[-50%] bg-cover bg-center bg-no-repeat transition-opacity duration-500 ease-in-out"
              style={{ backgroundImage: `url(${data?.homeImageUrl || ''})` }}
            />

            {/* 渐变遮罩 */}
            <div
              className="absolute top-0 left-1/2 flex h-full w-[752px] translate-x-[-50%] items-center justify-between transition-opacity duration-500 ease-in-out"
              style={{
                backgroundImage: `linear-gradient(90deg, rgba(${colors.leftColor}, 1) 0%, rgba(${colors.leftColor}, 0) 20%, rgba(${colors.rightColor}, 0) 80%, rgba(${colors.rightColor}, 1) 100%)`,
              }}
            >
              {/* <div className={cn('h-60 w-32', `bg-gradient-to-r from-[${colors.leftColor}] to-transparent`)} />
              <div className={cn('h-60 w-32', `bg-gradient-to-l from-[${colors.rightColor}] to-transparent`)} /> */}
            </div>
          </>
        )}

        {/* 底部渐变遮罩 */}
        <div className="to-background-default absolute inset-0 bg-linear-to-b from-transparent" />
        <canvas ref={canvasRef} style={{ display: 'none' }}></canvas>
      </div>
    </>
  )
}

export default UserBackground
