import { useState, useEffect, useCallback, useRef } from 'react'
import { MessageSquare, Search, RefreshCw } from 'lucide-react'
import { DirectMessageService } from '../services/api'
import { useSSE } from '../hooks/useSSE'

export interface Colleague {
  id: number
  name: string
  email: string
  availability: 'online' | 'busy' | 'offline'
  avatar_url: string | null
  unread_count: number
}

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

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

export default function CollaboratorsPanel({
  selected,
  onSelect,
  onStartDM,
  onNewDM,
}: {
  selected: number | null
  onSelect: (colleague: Colleague) => void
  onStartDM: (colleague: Colleague) => void
  /** Chamado quando chega dm.new para atualizar badge no pai */
  onNewDM?: (fromAccountId: number) => void
}) {
  const [colleagues, setColleagues] = useState<Colleague[]>([])
  const [loading, setLoading]       = useState(true)
  const [refreshing, setRefreshing] = useState(false)
  const [search, setSearch]         = useState('')
  const colleaguesRef               = useRef<Colleague[]>([])

  // Mantém ref sempre sincronizada para uso nos handlers SSE
  useEffect(() => { colleaguesRef.current = colleagues }, [colleagues])

  const load = useCallback(async (silent = false) => {
    if (!silent) setLoading(true)
    else setRefreshing(true)
    try {
      const data = await DirectMessageService.getColleagues()
      setColleagues(Array.isArray(data) ? data : [])
    } catch (err) {
      console.error('Erro ao carregar colaboradores:', err)
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }, [])

  // Carga inicial — sem polling
  useEffect(() => { load() }, [load])

  // SSE — atualiza presença em tempo real (sem requisições)
  const { addEventListener, removeEventListener } = useSSE()

  useEffect(() => {
    const handlePresence = (data: unknown) => {
      const { accountId, availability } = data as { accountId: number; availability: string }
      setColleagues(prev =>
        prev.map(c =>
          c.id === Number(accountId)
            ? { ...c, availability: availability as Colleague['availability'] }
            : c
        )
      )
    }

    const handleDmNew = (data: unknown) => {
      const { from } = data as { from: number }
      // Incrementar unread_count do remetente
      setColleagues(prev =>
        prev.map(c =>
          c.id === from
            ? { ...c, unread_count: c.unread_count + 1 }
            : c
        )
      )
      onNewDM?.(from)
    }

    addEventListener('presence.change', handlePresence)
    addEventListener('dm.new', handleDmNew)
    return () => {
      removeEventListener('presence.change', handlePresence)
      removeEventListener('dm.new', handleDmNew)
    }
  }, [addEventListener, removeEventListener, onNewDM])

  const filtered = colleagues.filter(c =>
    c.name.toLowerCase().includes(search.toLowerCase()) ||
    c.email.toLowerCase().includes(search.toLowerCase())
  )

  // Ordenar: online > busy > offline, depois alfabético
  const sorted = [...filtered].sort((a, b) => {
    const order = { online: 0, busy: 1, offline: 2 }
    const diff = (order[a.availability] ?? 2) - (order[b.availability] ?? 2)
    return diff !== 0 ? diff : a.name.localeCompare(b.name, 'pt-BR')
  })

  return (
    <div className="flex flex-col flex-1 min-h-0 bg-white">
      {/* Header */}
      <div className="flex-shrink-0 px-3 pt-3 pb-2 bg-[#f0f2f5] border-b border-[#e9edef]">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-xs font-semibold text-[#667781] uppercase tracking-wide">
            Colaboradores
          </h3>
          <button
            onClick={() => load(true)}
            disabled={refreshing}
            className="p-1 rounded-full hover:bg-[#e9edef] transition text-[#8696a0] disabled:opacity-40"
            title="Atualizar lista"
          >
            <RefreshCw size={11} className={refreshing ? 'animate-spin' : ''} />
          </button>
        </div>
        <div className="relative">
          <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-[#8696a0] pointer-events-none" />
          <input
            type="text"
            placeholder="Buscar..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full bg-white border border-[#d1d7db] rounded-lg pl-8 pr-2.5 py-1.5 text-[12px] text-[#111b21] placeholder:text-[#8696a0] focus:outline-none focus:ring-1 focus:ring-[#00a884]"
          />
        </div>
      </div>

      {/* Lista */}
      <div className="flex-1 overflow-y-auto">
        {loading ? (
          <div className="text-center py-8 text-[#8696a0] text-[12px]">Carregando...</div>
        ) : sorted.length === 0 ? (
          <div className="text-center py-8 text-[#8696a0] text-[12px]">
            {search ? 'Nenhum colaborador encontrado' : 'Nenhum colaborador'}
          </div>
        ) : (
          sorted.map((colleague) => (
            <button
              key={colleague.id}
              onClick={() => onSelect(colleague)}
              className={`w-full text-left flex items-center gap-2.5 px-3 py-2.5 border-b border-[#f0f2f5] hover:bg-[#f5f6f6] transition-colors
                ${selected === colleague.id ? 'bg-[#e7f5ff] border-l-4 border-l-[#00a884]' : ''}`}
            >
              {/* Avatar + indicador de status */}
              <div className="relative flex-shrink-0">
                {colleague.avatar_url ? (
                  <img src={colleague.avatar_url} alt={colleague.name} className="w-9 h-9 rounded-full object-cover" />
                ) : (
                  <div className="w-9 h-9 rounded-full bg-[#dfe5e7] flex items-center justify-center text-[#54656f] text-[12px] font-semibold">
                    {colleague.name.charAt(0).toUpperCase()}
                  </div>
                )}
                <span
                  className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-white ${AVAIL_COLOR[colleague.availability] ?? 'bg-slate-300'}`}
                />
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between gap-1">
                  <span className="text-[13px] font-medium text-[#111b21] truncate leading-tight">
                    {colleague.name}
                  </span>
                  {colleague.unread_count > 0 && (
                    <span className="flex-shrink-0 bg-[#25d366] text-white text-[9px] font-bold min-w-[16px] h-4 px-0.5 rounded-full flex items-center justify-center">
                      {colleague.unread_count > 9 ? '9+' : colleague.unread_count}
                    </span>
                  )}
                </div>
                <p className={`text-[11px] truncate leading-tight ${
                  colleague.availability === 'online'
                    ? 'text-green-600'
                    : colleague.availability === 'busy'
                      ? 'text-yellow-600'
                      : 'text-[#8696a0]'
                }`}>
                  {AVAIL_LABEL[colleague.availability]}
                </p>
              </div>

              {/* Botão DM */}
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  onStartDM(colleague)
                }}
                className="flex-shrink-0 p-1.5 rounded-lg text-[#8696a0] hover:bg-[#e9edef] hover:text-[#00a884] transition"
                title="Enviar mensagem"
              >
                <MessageSquare size={13} />
              </button>
            </button>
          ))
        )}
      </div>
    </div>
  )
}
