import { useState, useEffect, useCallback, useRef } from 'react'
import { Megaphone, Send, RefreshCw, AlertTriangle } from 'lucide-react'
import { BroadcastService, type BroadcastItem } from '../services/api'
import { useSSE } from '../hooks/useSSE'

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 atrás`
  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', year: '2-digit' })
}

function Avatar({ name, url }: { name: string | null; url?: string | null }) {
  if (url) return <img src={url} className="w-7 h-7 rounded-full object-cover flex-shrink-0" />
  const letter = name ? name.charAt(0).toUpperCase() : '?'
  return (
    <div className="w-7 h-7 rounded-full bg-amber-100 flex items-center justify-center text-amber-700 text-xs font-semibold flex-shrink-0">
      {letter}
    </div>
  )
}

export default function BroadcastPanel({
  accountId,
  role,
  onNewBroadcast,
  onSeen,
}: {
  accountId: number
  role: string
  /** Chamado quando broadcast recebido via SSE (para toast no pai) */
  onNewBroadcast?: (content: string) => void
  /** Chamado quando o painel é aberto para resetar badge */
  onSeen?: () => void
}) {
  const [items, setItems]       = useState<BroadcastItem[]>([])
  const [loading, setLoading]   = useState(true)
  const [content, setContent]   = useState('')
  const [sending, setSending]   = useState(false)
  const [confirm, setConfirm]   = useState(false)
  const bottomRef               = useRef<HTMLDivElement>(null)
  const { addEventListener, removeEventListener } = useSSE()
  const isManager = role === 'owner' || role === 'manager'

  // Resetar badge no pai ao montar o painel
  useEffect(() => { onSeen?.() }, [])

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const { items } = await BroadcastService.list()
      setItems([...items].reverse()) // mais antigos primeiro
      // Marcar como visto ao abrir o painel
      BroadcastService.markSeen().catch(() => {})
    } finally {
      setLoading(false)
    }
  }, [])

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

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

  // SSE — appenda broadcasts recebidos de outros em tempo real
  useEffect(() => {
    const handle = (data: unknown) => {
      const d = data as { id: number; from: number; content: string; created_at: string }
      if (d.from === accountId) return // já appendado otimisticamente
      const item: BroadcastItem = {
        id:            d.id,
        from_account:  d.from,
        content:       d.content,
        created_at:    d.created_at,
        sender_name:   null,
        sender_avatar: null,
      }
      setItems(prev => [...prev, item])
      onNewBroadcast?.(d.content)
    }
    addEventListener('broadcast.sent', handle)
    return () => removeEventListener('broadcast.sent', handle)
  }, [addEventListener, removeEventListener, accountId, onNewBroadcast])

  async function send() {
    if (!content.trim() || !isManager) return
    setSending(true)
    const text = content.trim()
    setContent('')
    setConfirm(false)
    try {
      const bc = await BroadcastService.send(text)
      setItems(prev => [...prev, bc])
    } catch {
      setContent(text)
    } finally {
      setSending(false)
    }
  }

  return (
    <div className="flex flex-col h-full bg-[#f0f2f5]">
      {/* Header */}
      <div className="flex-shrink-0 px-4 py-3 bg-white border-b border-[#e9edef] flex items-center gap-2">
        <div className="w-8 h-8 rounded-full bg-amber-100 flex items-center justify-center flex-shrink-0">
          <Megaphone size={16} className="text-amber-600" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-[#111b21]">Broadcast</p>
          <p className="text-[11px] text-[#8696a0]">Avisos para toda a equipe</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>

      {/* Lista de broadcasts */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {loading && items.length === 0 ? (
          <div className="text-center py-8 text-[#8696a0] text-sm">Carregando...</div>
        ) : items.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-[#8696a0] gap-2">
            <Megaphone size={28} className="opacity-30" />
            <p className="text-[13px]">Nenhum aviso ainda.</p>
            {isManager && <p className="text-[11px]">Use o campo abaixo para enviar um aviso para toda a equipe.</p>}
          </div>
        ) : (
          items.map(item => (
            <div
              key={item.id}
              className="bg-white rounded-xl shadow-sm border border-amber-100 px-4 py-3 flex gap-3"
            >
              <Avatar name={item.sender_name} url={item.sender_avatar} />
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between gap-2 mb-0.5">
                  <p className="text-[12px] font-semibold text-amber-700">
                    {item.sender_name ?? 'Sistema'}
                  </p>
                  <span className="text-[10px] text-[#8696a0] flex-shrink-0">
                    {formatTime(item.created_at)}
                  </span>
                </div>
                <p className="text-[13px] text-[#111b21] leading-relaxed whitespace-pre-wrap">
                  {item.content}
                </p>
              </div>
            </div>
          ))
        )}
        <div ref={bottomRef} />
      </div>

      {/* Input — apenas para owner/manager */}
      {isManager && (
        <div className="flex-shrink-0 bg-white border-t border-[#e9edef] px-4 py-3 space-y-2">
          {confirm && (
            <div className="flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
              <AlertTriangle size={13} className="text-amber-600 flex-shrink-0" />
              <p className="text-[12px] text-amber-700 flex-1">
                Isso enviará um aviso para <strong>todos os colaboradores</strong>. Confirmar?
              </p>
              <button
                onClick={send}
                disabled={sending}
                className="px-3 py-1 bg-amber-500 hover:bg-amber-600 disabled:opacity-40 text-white text-[11px] font-semibold rounded-lg transition"
              >
                {sending ? 'Enviando...' : 'Enviar'}
              </button>
              <button
                onClick={() => setConfirm(false)}
                className="px-2 py-1 text-[11px] text-[#54656f] hover:bg-[#e9edef] rounded-lg transition"
              >
                Cancelar
              </button>
            </div>
          )}
          <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(); if (content.trim()) setConfirm(true) }
              }}
              rows={1}
              placeholder="Aviso para toda a equipe..."
              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={() => { if (content.trim()) setConfirm(true) }}
              disabled={sending || !content.trim()}
              className="p-2.5 bg-amber-500 hover:bg-amber-600 disabled:opacity-40 text-white rounded-full transition flex-shrink-0"
            >
              <Send size={15} />
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
