/**
 * ChatHubWidget - Lista de sessoes de chat ativas usando Convex subscriptions
 *
 * Arquitetura:
 * - Usa useQuery do Convex React para subscription reativa (tempo real verdadeiro)
 * - Sem polling - todas as atualizacoes sao push-based via WebSocket
 * - Tauri usado apenas para gerenciamento de janelas
 */

import { useEffect, useState } from "react"
import { invoke } from "@tauri-apps/api/core"
import { Loader2, MessageCircle, ChevronUp, X, Minimize2 } from "lucide-react"
import { useMachineSessions, type MachineSession } from "./useConvexMachineQueries"

/**
 * Hub Widget - Lista todas as sessoes de chat ativas
 * Ao clicar em uma sessao, abre/foca a janela de chat daquele ticket
 */
export function ChatHubWidget() {
  // Inicializa baseado na altura real da janela (< 100px = minimizado)
  const [isMinimized, setIsMinimized] = useState(() => window.innerHeight < 100)

  // Convex subscription reativa
  const { sessions = [], isLoading, hasToken } = useMachineSessions()

  // Sincronizar estado minimizado com tamanho da janela
  useEffect(() => {
    const mountTime = Date.now()
    const STABILIZATION_DELAY = 500

    const handler = () => {
      if (Date.now() - mountTime < STABILIZATION_DELAY) {
        return
      }
      const h = window.innerHeight
      setIsMinimized(h < 100)
    }
    window.addEventListener("resize", handler)
    return () => window.removeEventListener("resize", handler)
  }, [])

  const handleSelectSession = async (ticketId: string, ticketRef: number) => {
    try {
      // Tauri 2.x auto-converts snake_case (Rust) to camelCase (JS)
      await invoke("open_chat_window", { ticketId, ticketRef })
      await invoke("close_hub_window")
    } catch (err) {
      console.error("open_chat_window FAILED:", err)
    }
  }

  const handleMinimize = async () => {
    setIsMinimized(true)
    try {
      await invoke("set_hub_minimized", { minimized: true })
    } catch (err) {
      console.error("Erro ao minimizar hub:", err)
    }
  }

  const handleExpand = async () => {
    try {
      await invoke("set_hub_minimized", { minimized: false })
      setTimeout(() => setIsMinimized(false), 100)
    } catch (err) {
      console.error("set_hub_minimized FAILED:", err)
      setIsMinimized(false)
    }
  }

  const handleClose = () => {
    invoke("close_hub_window").catch((err) => {
      console.error("Erro ao fechar janela do hub:", err)
    })
  }

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

  // Sem token
  if (!hasToken) {
    return (
      <div className="pointer-events-none flex h-full w-full items-end justify-end bg-transparent p-2">
        <div className="pointer-events-auto flex items-center gap-2 rounded-full bg-red-100 px-4 py-2 text-red-600 shadow-lg">
          <span className="text-sm font-medium">Token nao configurado</span>
        </div>
      </div>
    )
  }

  // Loading
  if (isLoading) {
    return (
      <div className="pointer-events-none flex h-full w-full items-end justify-end bg-transparent p-2">
        <div className="pointer-events-auto flex items-center gap-2 rounded-full bg-slate-200 px-4 py-2 text-slate-600 shadow-lg">
          <Loader2 className="size-4 animate-spin" />
          <span className="text-sm font-medium">Carregando...</span>
        </div>
      </div>
    )
  }

  // Sem sessoes ativas
  if (sessions.length === 0) {
    return (
      <div className="pointer-events-none flex h-full w-full items-end justify-end bg-transparent p-2">
        <div className="pointer-events-auto flex items-center gap-2 rounded-full bg-slate-200 px-4 py-2 text-slate-600 shadow-lg">
          <MessageCircle className="size-4" />
          <span className="text-sm font-medium">Sem chats</span>
        </div>
      </div>
    )
  }

  // Minimizado
  if (isMinimized) {
    return (
      <div className="pointer-events-none flex h-full w-full items-end justify-end bg-transparent pr-3">
        <button
          onClick={(e) => {
            e.stopPropagation()
            handleExpand()
          }}
          className="pointer-events-auto relative flex items-center gap-2 rounded-full bg-black px-4 py-2 text-white shadow-lg hover:bg-black/90"
        >
          <MessageCircle className="size-4" />
          <span className="text-sm font-medium">
            {sessions.length} chat{sessions.length !== 1 ? "s" : ""}
          </span>
          <span className="size-2 rounded-full bg-emerald-400" />
          <ChevronUp className="size-4" />
          {totalUnread > 0 && (
            <span className="absolute -right-1 -top-1 flex size-5 items-center justify-center rounded-full bg-red-500 text-xs font-bold">
              {totalUnread > 9 ? "9+" : totalUnread}
            </span>
          )}
        </button>
      </div>
    )
  }

  // Expandido
  return (
    <div className="flex h-full flex-col overflow-hidden rounded-2xl bg-white shadow-xl">
      {/* Header */}
      <div
        data-tauri-drag-region
        className="flex items-center justify-between border-b border-slate-200 bg-slate-50 px-4 py-3 rounded-t-2xl"
      >
        <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 Ativos</p>
            <p className="text-xs text-slate-500">
              {sessions.length} conversa{sessions.length !== 1 ? "s" : ""}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={handleMinimize}
            className="rounded-md p-1.5 text-slate-500 hover:bg-slate-100"
            aria-label="Minimizar lista de chats"
          >
            <Minimize2 className="size-4" />
          </button>
          <button
            onClick={handleClose}
            className="rounded-md p-1.5 text-slate-500 hover:bg-slate-100"
            aria-label="Fechar lista de chats"
          >
            <X className="size-4" />
          </button>
        </div>
      </div>

      {/* Lista de sessoes */}
      <div className="flex-1 overflow-y-auto p-2">
        <div className="space-y-2">
          {sessions.map((session) => (
            <SessionItem
              key={session.sessionId}
              session={session}
              onClick={() => handleSelectSession(session.ticketId, session.ticketRef)}
            />
          ))}
        </div>
      </div>
    </div>
  )
}

function SessionItem({
  session,
  onClick,
}: {
  session: MachineSession
  onClick: () => void
}) {
  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    onClick()
  }

  return (
    <button
      onClick={handleClick}
      className="flex w-full items-center gap-3 rounded-xl p-3 text-left transition hover:bg-slate-50"
    >
      {/* Avatar */}
      <div className="relative flex size-10 shrink-0 items-center justify-center rounded-full bg-black text-white">
        <MessageCircle className="size-5" />
        {/* Indicador online */}
        <span className="absolute -bottom-0.5 -right-0.5 size-3 rounded-full border-2 border-white bg-emerald-500" />
      </div>

      {/* Info */}
      <div className="min-w-0 flex-1">
        <div className="flex items-center justify-between gap-2">
          <p className="truncate text-sm font-medium text-slate-900">
            Ticket #{session.ticketRef}
          </p>
          <span className="shrink-0 text-xs text-slate-400">
            {formatRelativeTime(session.lastActivityAt)}
          </span>
        </div>
        <p className="truncate text-xs text-slate-500">
          {session.agentName}
        </p>
      </div>

      {/* Badge nao lidas */}
      {session.unreadCount > 0 && (
        <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-red-500 text-xs font-bold text-white">
          {session.unreadCount > 9 ? "9+" : session.unreadCount}
        </span>
      )}
    </button>
  )
}

function formatRelativeTime(timestamp: number): string {
  const now = Date.now()
  const diff = now - timestamp

  const minutes = Math.floor(diff / 60000)
  if (minutes < 1) return "agora"
  if (minutes < 60) return `${minutes}m`

  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}h`

  const days = Math.floor(hours / 24)
  return `${days}d`
}
