'use client'

import { useEffect, useRef, useState } from 'react'
import type { ChatMessage } from '@/lib/protocol'
import smilePreview from '@/assets/开心_01_难得灿烂笑.transparent.webp'
import { MessageBubble } from './MessageBubble'

interface MessageListProps {
  messages: ChatMessage[]
  aiTyping: boolean
}

export function MessageList({ messages, aiTyping }: MessageListProps) {
  const bottomRef = useRef<HTMLDivElement>(null)
  const dragRef = useRef<{
    pointerId: number
    startX: number
    startY: number
    originX: number
    originY: number
  } | null>(null)
  const [offset, setOffset] = useState({ x: 0, y: 0 })

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages.length, aiTyping])

  const handlePointerDown: React.PointerEventHandler<
    HTMLDivElement
  > = event => {
    dragRef.current = {
      pointerId: event.pointerId,
      startX: event.clientX,
      startY: event.clientY,
      originX: offset.x,
      originY: offset.y,
    }
    event.currentTarget.setPointerCapture(event.pointerId)
  }

  const handlePointerMove: React.PointerEventHandler<
    HTMLDivElement
  > = event => {
    const dragState = dragRef.current
    if (!dragState || dragState.pointerId !== event.pointerId) {
      return
    }

    setOffset({
      x: dragState.originX + event.clientX - dragState.startX,
      y: dragState.originY + event.clientY - dragState.startY,
    })
  }

  const handlePointerUp: React.PointerEventHandler<HTMLDivElement> = event => {
    if (dragRef.current?.pointerId === event.pointerId) {
      dragRef.current = null
      event.currentTarget.releasePointerCapture(event.pointerId)
    }
  }

  return (
    <div className="flex-1 space-y-3 overflow-y-auto px-4 py-4">
      {messages.length === 0 && (
        <div className="flex h-full flex-col items-center justify-center gap-4 text-center">
          <div className="rounded-3xl bg-amber-200 p-6 shadow-sm ring-1 ring-slate-300">
            <div
              className="rounded-2xl p-4"
              style={{
                backgroundColor: '#f8fafc',
                backgroundImage:
                  'linear-gradient(45deg, #cbd5e1 25%, transparent 25%), linear-gradient(-45deg, #cbd5e1 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #cbd5e1 75%), linear-gradient(-45deg, transparent 75%, #cbd5e1 75%)',
                backgroundPosition: '0 0, 0 12px, 12px -12px, -12px 0px',
                backgroundSize: '24px 24px',
              }}
            >
              <div
                onPointerDown={handlePointerDown}
                onPointerMove={handlePointerMove}
                onPointerUp={handlePointerUp}
                onPointerCancel={handlePointerUp}
                className="inline-block touch-none cursor-grab active:cursor-grabbing"
                style={{
                  transform: `translate(${offset.x}px, ${offset.y}px)`,
                }}
              >
                <img
                  src={smilePreview.src}
                  alt="transparent preview"
                  draggable={false}
                  className="h-auto w-full max-w-xs select-none object-contain"
                />
              </div>
            </div>
          </div>
          <div className="space-y-1">
            <p className="text-sm font-medium text-slate-600">
              透明背景预览，可拖动
            </p>
            <p className="text-sm text-slate-400">
              Send a message to start chatting
            </p>
          </div>
        </div>
      )}
      {messages.map(msg => (
        <MessageBubble key={msg.id} message={msg} />
      ))}
      {aiTyping && (
        <div className="flex justify-start">
          <div className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-2.5">
            <div className="flex items-center gap-1">
              <span className="inline-block h-2 w-2 animate-bounce rounded-full bg-slate-400 [animation-delay:0ms]" />
              <span className="inline-block h-2 w-2 animate-bounce rounded-full bg-slate-400 [animation-delay:150ms]" />
              <span className="inline-block h-2 w-2 animate-bounce rounded-full bg-slate-400 [animation-delay:300ms]" />
            </div>
          </div>
        </div>
      )}
      <div ref={bottomRef} />
    </div>
  )
}
