import { useState, useEffect, useCallback, useRef } from 'react'
import { ArrowLeft, Send, RefreshCw } from 'lucide-react'
import { DirectMessageService } from '../services/api'
import { useSSE } from '../hooks/useSSE'
import { type Colleague } from './CollaboratorsPanel'

interface Message {
  id: number
  from_account: number
  to_account: number
  content: string
  read_at: string | null
  created_at: string
}

const AVAIL_LABEL: Record<string, string> = {
  online: 'Online',
  busy: 'Ocupado',
  away: 'Ausente',
  offline: 'Offline',
}

function Avatar({ name, url, size = 8 }: { name: string | null; url?: string | null; size?: number }) {
  const s = `w-${size} h-${size}`
  if (url) return <img src={url} className={`${s} rounded-full object-cover flex-shrink-0`} />
  const letter = name ? name.charAt(0).toUpperCase() : '?'
  return (
    <div className={`${s} rounded-full bg-[#dfe5e7] flex items-center justify-center text-[#54656f] text-xs font-semibold flex-shrink-0`}>
      {letter}
    </div>
  )
}

function formatTime(iso: string): string {
  const d = new Date(iso)
  const now = new Date()
  const diff = (now.getTime() - d.getTime()) / 1000
  if (diff < 60)    return 'agora'
  if (diff < 3600)  return `${Math.floor(diff/60)}m`
  if (diff < 86400) return d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' })
}

export default function DMConversationView({
  colleague,
  accountId,
  onBack,
}: {
  colleague: Colleague
  accountId: number
  onBack: () => void
}) {
  const [messages, setMessages] = useState<Message[]>([])
  const [loading, setLoading] = useState(true)
  const [content, setContent] = useState('')
  const [sending, setSending] = useState(false)
  const bottomRef = useRef<HTMLDivElement>(null)
  const { addEventListener, removeEventListener } = useSSE()

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const msgs = await DirectMessageService.getConversation(colleague.id, 50)
      setMessages(msgs)
      // Mark as read when opening conversation
      if (msgs.length > 0) {
        // Mark unread messages as read
        const unreadMsgs = msgs.filter((m: Message) => m.to_account === accountId && !m.read_at)
        for (const msg of unreadMsgs) {
          await DirectMessageService.markAsRead(msg.id)
        }
      }
    } finally {
      setLoading(false)
    }
  }, [colleague.id, accountId])

  useEffect(() => {
    load()
  }, [])

  // SSE — appenda mensagens recebidas em tempo real
  useEffect(() => {
    const handleDmNew = (data: unknown) => {
      const { id, from, to, content: msgContent, created_at } = data as {
        id: number; from: number; to: number; content: string; created_at: string
      }
      if (from !== colleague.id) return
      const newMsg: Message = {
        id,
        from_account: from,
        to_account:   to,
        content:      msgContent,
        read_at:      new Date().toISOString(),
        created_at,
      }
      setMessages(prev => [...prev, newMsg])
      DirectMessageService.markAsRead(id).catch(() => {})
    }
    addEventListener('dm.new', handleDmNew)
    return () => removeEventListener('dm.new', handleDmNew)
  }, [addEventListener, removeEventListener, colleague.id])

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

  async function send() {
    if (!content.trim()) return
    setSending(true)
    const text = content.trim()
    setContent('')
    try {
      const msg: Message = await DirectMessageService.send(colleague.id, text)
      setMessages(prev => [...prev, msg])
    } catch {
      setContent(text) // restaura em caso de erro
    } finally {
      setSending(false)
    }
  }

  return (
    <div className="flex flex-col h-full bg-[#f0f2f5]">
      {/* Header */}
      <div className="flex-shrink-0 px-3 py-3 bg-white border-b border-[#e9edef] flex items-center gap-2">
        <button onClick={onBack} className="p-1 rounded-full hover:bg-[#e9edef] transition text-[#54656f]">
          <ArrowLeft size={18} />
        </button>
        <Avatar name={colleague.name} url={colleague.avatar_url} size={8} />
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-[#111b21] truncate">{colleague.name}</p>
          <p className="text-[11px] text-[#8696a0]">{AVAIL_LABEL[colleague.availability]}</p>
        </div>
        <button
          onClick={load}
          className="p-1.5 rounded-full hover:bg-[#e9edef] transition text-[#8696a0]">
          <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
        </button>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-3 space-y-2">
        {loading && messages.length === 0 ? (
          <div className="text-center py-8 text-[#8696a0] text-sm">Carregando conversa...</div>
        ) : messages.length === 0 ? (
          <div className="text-center py-8 text-[#8696a0] text-sm">
            Nenhuma mensagem ainda. Comece uma conversa!
          </div>
        ) : (
          messages.map((msg) => {
            const isMe = msg.from_account === accountId
            return (
              <div key={msg.id} className={`flex gap-2 ${isMe ? 'flex-row-reverse' : ''}`}>
                {!isMe && <Avatar name={colleague.name} url={colleague.avatar_url} size={7} />}
                <div className={`max-w-[82%] flex flex-col gap-0.5 ${isMe ? 'items-end' : 'items-start'}`}>
                  <div
                    className={`px-3 py-2 rounded-2xl text-[13px] leading-relaxed whitespace-pre-wrap shadow-sm
                      ${
                        isMe
                          ? 'bg-[#d9fdd3] text-[#111b21] rounded-tr-sm'
                          : 'bg-white text-[#111b21] rounded-tl-sm'
                      }`}>
                    {msg.content}
                  </div>
                  <p className="text-[10px] text-[#8696a0] px-1">{formatTime(msg.created_at)}</p>
                </div>
              </div>
            )
          })
        )}
        <div ref={bottomRef} />
      </div>

      {/* Input */}
      <div className="flex-shrink-0 px-3 py-2 bg-white border-t border-[#e9edef]">
        <div className="flex gap-2 items-end">
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault()
                send()
              }
            }}
            rows={1}
            placeholder="Digite uma mensagem"
            className="flex-1 bg-[#f0f2f5] border-0 rounded-xl px-3 py-2.5 text-[13px] text-[#111b21] placeholder-[#8696a0] focus:outline-none resize-none"
            style={{ minHeight: 40, maxHeight: 100 }}
          />
          <button
            onClick={send}
            disabled={sending || !content.trim()}
            className="p-2.5 bg-[#00a884] hover:bg-[#008f72] disabled:opacity-40 text-white rounded-full transition flex-shrink-0">
            <Send size={15} />
          </button>
        </div>
      </div>
    </div>
  )
}
