import { useState, useEffect, useCallback, useRef } from 'react'
import { ArrowLeft, Send, Users } from 'lucide-react'
import { GroupChatService, type GroupChat, type GroupMessage } from '../services/api'
import { useSSE } from '../hooks/useSSE'

function Avatar({ name, url, size = 7 }: { 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 GroupChatView({
  group,
  accountId,
  onBack,
}: {
  group: GroupChat
  accountId: number
  onBack: () => void
}) {
  const [messages, setMessages]         = useState<GroupMessage[]>([])
  const [loading, setLoading]           = useState(true)
  const [content, setContent]           = useState('')
  const [sending, setSending]           = useState(false)
  const [showMembers, setShowMembers]   = useState(false)
  const [members, setMembers]           = useState<{ id: number; name: string; avatar_url: string | null; availability: string }[]>([])
  const bottomRef                        = useRef<HTMLDivElement>(null)
  const { addEventListener, removeEventListener } = useSSE()

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const msgs = await GroupChatService.getMessages(group.id, 50)
      setMessages(msgs)
    } finally {
      setLoading(false)
    }
  }, [group.id])

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

  // SSE — appenda mensagens recebidas de outros membros em tempo real
  useEffect(() => {
    const handleGroupMsg = (data: unknown) => {
      const d = data as {
        id: number; group_chat_id: number; from: number
        content: string; created_at: string
      }
      if (d.group_chat_id !== group.id) return
      if (d.from === accountId) return // já appendado otimisticamente
      const newMsg: GroupMessage = {
        id:            d.id,
        from_account:  d.from,
        content:       d.content,
        created_at:    d.created_at,
        sender_name:   null,
        sender_avatar: null,
      }
      setMessages(prev => [...prev, newMsg])
    }
    addEventListener('group_message.new', handleGroupMsg)
    return () => removeEventListener('group_message.new', handleGroupMsg)
  }, [addEventListener, removeEventListener, group.id, accountId])

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

  async function send() {
    if (!content.trim()) return
    setSending(true)
    const text = content.trim()
    setContent('')
    try {
      const msg = await GroupChatService.sendMessage(group.id, text)
      setMessages(prev => [...prev, msg])
    } catch {
      setContent(text)
    } finally {
      setSending(false)
    }
  }

  async function toggleMembers() {
    if (!showMembers && members.length === 0) {
      const data = await GroupChatService.getMembers(group.id)
      setMembers(data)
    }
    setShowMembers(v => !v)
  }

  const AVAIL_COLOR: Record<string, string> = {
    online: 'bg-green-500',
    busy:   'bg-yellow-500',
    offline: 'bg-slate-300',
  }

  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>
        <div
          className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-bold flex-shrink-0"
          style={{ backgroundColor: group.color }}
        >
          {group.name.charAt(0).toUpperCase()}
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-[#111b21] truncate">{group.name}</p>
          <p className="text-[11px] text-[#8696a0]">Grupo · setor</p>
        </div>
        <button
          onClick={toggleMembers}
          className={`p-1.5 rounded-full transition ${showMembers ? 'bg-[#e9edef] text-[#00a884]' : 'hover:bg-[#e9edef] text-[#8696a0]'}`}
          title="Ver membros"
        >
          <Users size={15} />
        </button>
      </div>

      {/* Painel de membros (colapsável) */}
      {showMembers && (
        <div className="flex-shrink-0 bg-white border-b border-[#e9edef] px-3 py-2">
          <p className="text-[11px] font-semibold text-[#667781] uppercase mb-1.5">Membros</p>
          <div className="flex flex-wrap gap-2">
            {members.map(m => (
              <div key={m.id} className="flex items-center gap-1.5">
                <div className="relative">
                  <Avatar name={m.name} url={m.avatar_url} size={6} />
                  <span className={`absolute bottom-0 right-0 w-2 h-2 rounded-full border border-white ${AVAIL_COLOR[m.availability] ?? 'bg-slate-300'}`} />
                </div>
                <span className="text-[12px] text-[#111b21]">{m.name}</span>
              </div>
            ))}
            {members.length === 0 && (
              <span className="text-[12px] text-[#8696a0]">Nenhum membro</span>
            )}
          </div>
        </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 mensagens...</div>
        ) : messages.length === 0 ? (
          <div className="text-center py-8 text-[#8696a0] text-sm">
            Nenhuma mensagem ainda. Inicie a conversa do setor!
          </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={msg.sender_name} url={msg.sender_avatar} size={7} />
                )}
                <div className={`max-w-[82%] flex flex-col gap-0.5 ${isMe ? 'items-end' : 'items-start'}`}>
                  {!isMe && msg.sender_name && (
                    <p className="text-[11px] font-semibold text-[#54656f] px-1">{msg.sender_name}</p>
                  )}
                  <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={`Mensagem para ${group.name}`}
            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>
  )
}
