'use client'

import { useEffect, useRef, useState } from 'react'
import Image from 'next/image'
import { useApiKeyAvatar } from '@/hooks/useApiKeyAvatar'
import { useRelay } from '@/hooks/useRelay'
import type { Emoji } from '@/hooks/useAvatars'
import { resolveAvatarEmoji } from '@/lib/avatarEmoji'
import smilePreview from '@/assets/开心_01_难得灿烂笑.transparent.webp'

const STORAGE_KEY = 'floating-avatar-position'
const SIZE_STORAGE_KEY = 'floating-avatar-size'
const DEFAULT_SIZE = 120
const MIN_SIZE = 60
const MAX_SIZE = 1000 // 最大高度 1000px
const IMAGE_ASPECT_RATIO = 360 / 640 // 原始图片宽高比 (宽/高)

interface FloatingAvatarProps {
  apikeyId: string | null
}

export function FloatingAvatar({ apikeyId }: FloatingAvatarProps) {
  const { getBoundAvatar } = useApiKeyAvatar()
  const { avatarEvent } = useRelay()
  const [emojis, setEmojis] = useState<Emoji[]>([])
  const [imageUrl, setImageUrl] = useState<string | null>(null)
  const [imageAlt, setImageAlt] = useState('Virtual Avatar')
  const [position, setPosition] = useState({ x: 16, y: 16 })
  const [size, setSize] = useState(DEFAULT_SIZE) // 这是高度
  const [isDragging, setIsDragging] = useState(false)
  const [isResizing, setIsResizing] = useState(false)
  const [isActive, setIsActive] = useState(false)
  const dragRef = useRef<{ startX: number; startY: number; initialX: number; initialY: number } | null>(null)
  const resizeRef = useRef<{ startX: number; startY: number; initialSize: number } | null>(null)

  // 根据高度计算宽度，保持宽高比
  const width = Math.round(size * IMAGE_ASPECT_RATIO)

  // 从 localStorage 恢复位置和大小
  useEffect(() => {
    setPosition(current => ({
      x: current.x,
      y: Math.min(current.y || window.innerHeight - 136, window.innerHeight - 136),
    }))

    const savedPos = localStorage.getItem(STORAGE_KEY)
    if (savedPos) {
      try {
        const parsed = JSON.parse(savedPos)
        setPosition(parsed)
      } catch (e) {
        console.error('Failed to parse saved position:', e)
      }
    }

    const savedSize = localStorage.getItem(SIZE_STORAGE_KEY)
    if (savedSize) {
      try {
        const parsed = parseInt(savedSize, 10)
        if (!isNaN(parsed)) setSize(parsed)
      } catch (e) {
        console.error('Failed to parse saved size:', e)
      }
    }
  }, [])

  useEffect(() => {
    if (!apikeyId) {
      setEmojis([])
      setImageUrl(null)
      setImageAlt('Virtual Avatar')
      return
    }

    let cancelled = false

    void (async () => {
      try {
        const data = await getBoundAvatar(apikeyId)
        if (cancelled) return

        setEmojis(data.emojis || [])
        setImageAlt(data.avatar?.name ?? 'Virtual Avatar')
      } catch {
        if (cancelled) return
        setEmojis([])
        setImageUrl(null)
        setImageAlt('Virtual Avatar')
      }
    })()

    return () => {
      cancelled = true
    }
  }, [apikeyId, getBoundAvatar])

  useEffect(() => {
    const matchedEmoji = resolveAvatarEmoji(emojis, avatarEvent)
    setImageUrl(matchedEmoji?.url ?? null)
  }, [emojis, avatarEvent])

  // 保存位置到 localStorage
  const savePosition = (pos: { x: number; y: number }) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(pos))
  }

  // 保存大小到 localStorage
  const saveSize = (newSize: number) => {
    localStorage.setItem(SIZE_STORAGE_KEY, newSize.toString())
  }

  const handleMouseDown = (e: React.MouseEvent) => {
    // 如果点击的是边框区域，不触发拖动
    if ((e.target as HTMLElement).classList.contains('resize-border')) {
      return
    }

    e.preventDefault()
    e.stopPropagation()

    // 如果还未激活，先激活
    if (!isActive) {
      setIsActive(true)
    }

    setIsDragging(true)
    dragRef.current = {
      startX: e.clientX,
      startY: e.clientY,
      initialX: position.x,
      initialY: position.y,
    }
  }

  const handleResizeMouseDown = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsResizing(true)
    resizeRef.current = {
      startX: e.clientX,
      startY: e.clientY,
      initialSize: size,
    }
  }

  // 点击外部区域取消激活
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      if (!target.closest('.floating-avatar-container')) {
        setIsActive(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  useEffect(() => {
    if (!isDragging) return

    const handleMouseMove = (e: MouseEvent) => {
      if (!dragRef.current) return

      const deltaX = e.clientX - dragRef.current.startX
      const deltaY = e.clientY - dragRef.current.startY

      const newX = dragRef.current.initialX + deltaX
      const newY = dragRef.current.initialY + deltaY

      // 限制在视口范围内
      const maxX = window.innerWidth - width
      const maxY = window.innerHeight - size

      const boundedX = Math.max(0, Math.min(newX, maxX))
      const boundedY = Math.max(0, Math.min(newY, maxY))

      setPosition({ x: boundedX, y: boundedY })
    }

    const handleMouseUp = () => {
      setIsDragging(false)
      dragRef.current = null
      savePosition(position)
    }

    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)

    return () => {
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
  }, [isDragging, position, size, width])

  useEffect(() => {
    if (!isResizing) return

    const handleMouseMove = (e: MouseEvent) => {
      if (!resizeRef.current) return

      const deltaX = e.clientX - resizeRef.current.startX
      const deltaY = e.clientY - resizeRef.current.startY
      const delta = Math.max(deltaX, deltaY)

      const newSize = resizeRef.current.initialSize + delta
      const boundedSize = Math.max(MIN_SIZE, Math.min(newSize, MAX_SIZE))

      setSize(boundedSize)
    }

    const handleMouseUp = () => {
      setIsResizing(false)
      resizeRef.current = null
      saveSize(size)
    }

    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)

    return () => {
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
    }
  }, [isResizing, size])

  return (
    <div
      className="floating-avatar-container fixed z-[9999]"
      style={{
        left: `${position.x}px`,
        top: `${position.y}px`,
        width: `${width}px`,
        height: `${size}px`,
      }}
    >
      {/* 主图像区域 */}
      <div
        className="absolute inset-0 cursor-move"
        onMouseDown={handleMouseDown}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt={imageAlt}
            draggable={false}
            className="select-none w-full h-full pointer-events-none object-contain"
            onError={() => {
              const fallbackEmoji = resolveAvatarEmoji(emojis, { type: 'default' })
              setImageUrl(fallbackEmoji?.url ?? null)
            }}
          />
        ) : (
          <Image
            src={smilePreview}
            alt={imageAlt}
            width={width}
            height={size}
            draggable={false}
            className="select-none w-full h-full pointer-events-none object-contain"
          />
        )}
      </div>

      {/* 激活状态的边框 */}
      {isActive && (
        <>
          {/* 边框视觉效果 */}
          <div className="absolute inset-0 border-2 border-blue-400 pointer-events-none rounded" />

          {/* 上边框 */}
          <div
            className="resize-border absolute top-0 left-0 right-0 h-2 cursor-ns-resize hover:bg-blue-400/30 z-10"
            onMouseDown={handleResizeMouseDown}
          />
          {/* 右边框 */}
          <div
            className="resize-border absolute top-0 right-0 bottom-0 w-2 cursor-ew-resize hover:bg-blue-400/30 z-10"
            onMouseDown={handleResizeMouseDown}
          />
          {/* 下边框 */}
          <div
            className="resize-border absolute bottom-0 left-0 right-0 h-2 cursor-ns-resize hover:bg-blue-400/30 z-10"
            onMouseDown={handleResizeMouseDown}
          />
          {/* 左边框 */}
          <div
            className="resize-border absolute top-0 left-0 bottom-0 w-2 cursor-ew-resize hover:bg-blue-400/30 z-10"
            onMouseDown={handleResizeMouseDown}
          />
          {/* 右下角 */}
          <div
            className="resize-border absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize hover:bg-blue-400/50 z-10"
            onMouseDown={handleResizeMouseDown}
          />
        </>
      )}
    </div>
  )
}
