"use client"

import { useMemo } from "react"
import { MessageCircle, X } from "lucide-react"
import { ChatSessionItem } from "./chat-session-item"

type ChatSession = {
  ticketId: string
  ticketRef: number
  ticketSubject: string
  sessionId: string
  agentId: string
  unreadCount: number
  lastActivityAt: number
  machineHostname?: string | null
  machineOnline?: boolean
}

type ChatSessionListProps = {
  sessions: ChatSession[]
  activeTicketId?: string | null
  onSelectSession: (ticketId: string) => void
  onClose: () => void
  onMinimize: () => void
}

export function ChatSessionList({
  sessions,
  activeTicketId,
  onSelectSession,
  onClose,
  onMinimize,
}: ChatSessionListProps) {
  // Ordenar: nao lidos primeiro, depois por ultima atividade (desc)
  const sortedSessions = useMemo(() => {
    return [...sessions].sort((a, b) => {
      // Nao lidos primeiro
      if (a.unreadCount > 0 && b.unreadCount === 0) return -1
      if (a.unreadCount === 0 && b.unreadCount > 0) return 1
      // Depois por ultima atividade (mais recente primeiro)
      return b.lastActivityAt - a.lastActivityAt
    })
  }, [sessions])

  const totalUnread = sessions.reduce((sum, s) => sum + s.unreadCount, 0)

  return (
    <div className="flex h-full flex-col">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-slate-200 bg-white px-4 py-3">
        <div className="flex items-center gap-3">
          <div className="flex size-10 items-center justify-center rounded-full bg-black text-white">
            <MessageCircle className="size-5" />
          </div>
          <div>
            <p className="text-sm font-semibold text-slate-900">Chats</p>
            <p className="text-xs text-slate-500">
              {sessions.length} conversa{sessions.length !== 1 ? "s" : ""} ativa{sessions.length !== 1 ? "s" : ""}
              {totalUnread > 0 && (
                <span className="ml-1 text-red-500">
                  ({totalUnread} não lida{totalUnread !== 1 ? "s" : ""})
                </span>
              )}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={onMinimize}
            className="rounded-md p-1.5 text-slate-500 hover:bg-slate-100"
          >
            <svg className="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
            </svg>
          </button>
          <button
            onClick={onClose}
            className="rounded-md p-1.5 text-slate-500 hover:bg-slate-100"
          >
            <X className="size-4" />
          </button>
        </div>
      </div>

      {/* Lista de sessoes */}
      <div className="flex-1 overflow-y-auto bg-white">
        {sortedSessions.length === 0 ? (
          <div className="flex h-full flex-col items-center justify-center p-4 text-center">
            <div className="flex size-12 items-center justify-center rounded-full bg-slate-100">
              <MessageCircle className="size-6 text-slate-400" />
            </div>
            <p className="mt-3 text-sm font-medium text-slate-600">Nenhum chat ativo</p>
            <p className="mt-1 text-xs text-slate-400">
              Inicie um chat em um ticket para comecar
            </p>
          </div>
        ) : (
          sortedSessions.map((session) => (
            <ChatSessionItem
              key={session.ticketId}
              session={session}
              isActive={session.ticketId === activeTicketId}
              onClick={() => onSelectSession(session.ticketId)}
            />
          ))
        )}
      </div>
    </div>
  )
}
