"use client"

import { useState, useMemo } from "react"
import { useQuery, useAction } from "convex/react"
import { format, isToday, isYesterday, startOfDay } from "date-fns"
import { ptBR } from "date-fns/locale"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { useAuth } from "@/lib/auth-client"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Spinner } from "@/components/ui/spinner"
import { cn } from "@/lib/utils"
import {
  MessageCircle,
  ChevronDown,
  ChevronRight,
  User,
  Clock,
  Download,
  FileText,
  Paperclip,
  Calendar,
} from "lucide-react"

type ChatHistoryProps = {
  ticketId: string
}

type ChatMessage = {
  id: string
  body: string
  authorName: string
  authorId: string
  createdAt: number
  attachments: Array<{
    storageId: string
    name: string
    type: string | null
  }>
}

type ChatSession = {
  sessionId: string
  agentName: string
  agentEmail: string | null
  agentAvatarUrl: string | null
  machineName: string
  status: string
  startedAt: number
  endedAt: number | null
  messageCount: number
  messages: ChatMessage[]
}

type DayGroup = {
  date: Date
  dateKey: string
  label: string
  sessions: ChatSession[]
  totalMessages: number
}

const MESSAGES_PER_PAGE = 20
const DAYS_PER_PAGE = 5

function formatDuration(minutes: number): string {
  if (minutes < 60) {
    return `${minutes} min`
  }
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  if (mins === 0) {
    return `${hours}h`
  }
  return `${hours}h ${mins}min`
}

function formatDayLabel(date: Date): string {
  if (isToday(date)) {
    return "Hoje"
  }
  if (isYesterday(date)) {
    return "Ontem"
  }
  return format(date, "dd 'de' MMMM 'de' yyyy", { locale: ptBR })
}

function MessageAttachmentPreview({ attachment }: { attachment: { storageId: string; name: string; type: string | null } }) {
  const getFileUrl = useAction(api.files.getUrl)
  const [loading, setLoading] = useState(false)

  const handleDownload = async () => {
    setLoading(true)
    try {
      const url = await getFileUrl({ storageId: attachment.storageId as Id<"_storage"> })
      if (url) {
        const a = document.createElement("a")
        a.href = url
        a.download = attachment.name
        a.target = "_blank"
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
    } catch (error) {
      console.error("Erro ao baixar arquivo:", error)
    } finally {
      setLoading(false)
    }
  }

  const isImage = attachment.type?.startsWith("image/")

  return (
    <button
      onClick={handleDownload}
      disabled={loading}
      className="flex items-center gap-1.5 rounded-md border border-slate-200 bg-slate-50 px-2 py-1 text-xs hover:bg-slate-100 disabled:opacity-50"
    >
      {loading ? (
        <Spinner className="size-3" />
      ) : isImage ? (
        <FileText className="size-3 text-slate-500" />
      ) : (
        <Paperclip className="size-3 text-slate-500" />
      )}
      <span className="max-w-[100px] truncate">{attachment.name}</span>
      <Download className="size-3 text-slate-400" />
    </button>
  )
}

function ChatSessionCard({ session, isExpanded, onToggle }: { session: ChatSession; isExpanded: boolean; onToggle: () => void }) {
  const [visibleMessages, setVisibleMessages] = useState(MESSAGES_PER_PAGE)

  const isActive = session.status === "ACTIVE"
  const duration = session.endedAt
    ? Math.round((session.endedAt - session.startedAt) / 60000)
    : Math.round((Date.now() - session.startedAt) / 60000)

  const loadMore = () => {
    setVisibleMessages((prev) => prev + MESSAGES_PER_PAGE)
  }

  const displayedMessages = session.messages.slice(0, visibleMessages)
  const hasMore = session.messages.length > visibleMessages

  return (
    <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
      {/* Header da sessão */}
      <button
        onClick={onToggle}
        className="flex w-full items-center justify-between gap-3 px-4 py-3 text-left hover:bg-slate-50 transition-colors"
      >
        <div className="flex items-center gap-3">
          <div
            className={cn(
              "flex size-9 items-center justify-center rounded-full",
              isActive ? "bg-emerald-100 text-emerald-600" : "bg-slate-100 text-slate-600"
            )}
          >
            <MessageCircle className="size-4" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <p className="text-sm font-medium text-slate-900">
                Chat com {session.agentName}
              </p>
              {isActive && (
                <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700">
                  <span className="size-1.5 rounded-full bg-emerald-500 animate-pulse" />
                  Ativo
                </span>
              )}
            </div>
            <div className="flex items-center gap-2 text-xs text-slate-500">
              <span>{format(session.startedAt, "HH:mm", { locale: ptBR })}</span>
              <span>-</span>
              <span>{session.messageCount} mensagens</span>
              <span>-</span>
              <span>{formatDuration(duration)}</span>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {isExpanded ? (
            <ChevronDown className="size-4 text-slate-400" />
          ) : (
            <ChevronRight className="size-4 text-slate-400" />
          )}
        </div>
      </button>

      {/* Mensagens */}
      {isExpanded && (
        <div className="border-t border-slate-100">
          {session.messages.length === 0 ? (
            <div className="flex items-center justify-center py-6 text-sm text-slate-400">
              Nenhuma mensagem nesta sessão
            </div>
          ) : (
            <>
              <div className="max-h-[400px] overflow-y-auto p-4 space-y-3 bg-slate-50/50">
                {displayedMessages.map((msg) => {
                  // Verificar se eh do agente (nao eh da maquina)
                  const isAgent = msg.authorName === session.agentName

                  return (
                    <div
                      key={msg.id}
                      className={cn("flex gap-2", isAgent ? "flex-row" : "flex-row-reverse")}
                    >
                      <div
                        className={cn(
                          "flex size-7 shrink-0 items-center justify-center rounded-full",
                          isAgent ? "bg-slate-100 text-slate-600" : "bg-slate-200 text-slate-600"
                        )}
                      >
                        {isAgent ? <MessageCircle className="size-3.5" /> : <User className="size-3.5" />}
                      </div>
                      <div
                        className={cn(
                          "max-w-[80%] rounded-2xl px-3 py-2",
                          isAgent
                            ? "rounded-bl-md bg-white border border-slate-200 text-slate-900"
                            : "rounded-br-md bg-slate-700 text-white"
                        )}
                      >
                        <p className="mb-0.5 text-xs font-medium opacity-70">
                          {msg.authorName}
                        </p>
                        {msg.body && (
                          <p className="whitespace-pre-wrap text-sm">{msg.body}</p>
                        )}
                        {msg.attachments.length > 0 && (
                          <div className="mt-2 flex flex-wrap gap-1">
                            {msg.attachments.map((att, i) => (
                              <MessageAttachmentPreview key={i} attachment={att} />
                            ))}
                          </div>
                        )}
                        <p className={cn("mt-1 text-right text-xs", isAgent ? "text-slate-400" : "text-white/60")}>
                          {format(msg.createdAt, "HH:mm", { locale: ptBR })}
                        </p>
                      </div>
                    </div>
                  )
                })}
              </div>

              {/* Carregar mais */}
              {hasMore && (
                <div className="border-t border-slate-100 p-3 text-center">
                  <Button variant="ghost" size="sm" onClick={loadMore}>
                    Carregar mais ({session.messages.length - visibleMessages} restantes)
                  </Button>
                </div>
              )}
            </>
          )}

          {/* Rodape com info de encerramento */}
          {session.endedAt && (
            <div className="border-t border-slate-100 px-4 py-2 bg-slate-50">
              <p className="flex items-center gap-1.5 text-xs text-slate-500">
                <Clock className="size-3" />
                Encerrado em {format(session.endedAt, "dd/MM/yyyy 'as' HH:mm", { locale: ptBR })}
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

function DayGroupCard({
  dayGroup,
  isExpanded,
  onToggle,
  expandedSessions,
  onToggleSession
}: {
  dayGroup: DayGroup
  isExpanded: boolean
  onToggle: () => void
  expandedSessions: Set<string>
  onToggleSession: (sessionId: string) => void
}) {
  return (
    <div className="space-y-2">
      {/* Header do dia */}
      <button
        onClick={onToggle}
        className="flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left hover:bg-slate-50 transition-colors"
      >
        <div className="flex items-center gap-2">
          <Calendar className="size-4 text-slate-400" />
          <span className="text-sm font-medium text-slate-700">{dayGroup.label}</span>
          <span className="text-xs text-slate-500">
            ({dayGroup.sessions.length} {dayGroup.sessions.length === 1 ? "sessão" : "sessões"} - {dayGroup.totalMessages} mensagens)
          </span>
        </div>
        {isExpanded ? (
          <ChevronDown className="size-4 text-slate-400" />
        ) : (
          <ChevronRight className="size-4 text-slate-400" />
        )}
      </button>

      {/* Sessões do dia */}
      {isExpanded && (
        <div className="space-y-2 pl-2">
          {dayGroup.sessions.map((session) => (
            <ChatSessionCard
              key={session.sessionId}
              session={session}
              isExpanded={expandedSessions.has(session.sessionId)}
              onToggle={() => onToggleSession(session.sessionId)}
            />
          ))}
        </div>
      )}
    </div>
  )
}

export function TicketChatHistory({ ticketId }: ChatHistoryProps) {
  const { convexUserId } = useAuth()
  const [expandedDays, setExpandedDays] = useState<Set<string>>(new Set())
  const [expandedSessions, setExpandedSessions] = useState<Set<string>>(new Set())
  const [visibleDays, setVisibleDays] = useState(DAYS_PER_PAGE)

  const chatHistory = useQuery(
    api.liveChat.getTicketChatHistory,
    convexUserId
      ? { ticketId: ticketId as Id<"tickets">, viewerId: convexUserId as Id<"users"> }
      : "skip"
  )

  // Agrupar sessoes por dia
  const sessions = chatHistory?.sessions
  const dayGroups = useMemo(() => {
    if (!sessions) return []

    const groups = new Map<string, DayGroup>()

    sessions.forEach((session: ChatSession) => {
      const sessionDate = new Date(session.startedAt)
      const dayStart = startOfDay(sessionDate)
      const dateKey = dayStart.toISOString()

      if (!groups.has(dateKey)) {
        groups.set(dateKey, {
          date: dayStart,
          dateKey,
          label: formatDayLabel(dayStart),
          sessions: [],
          totalMessages: 0,
        })
      }

      const group = groups.get(dateKey)!
      group.sessions.push(session)
      group.totalMessages += session.messageCount
    })

    // Ordenar sessoes dentro de cada grupo por hora (mais recente primeiro)
    groups.forEach((group) => {
      group.sessions.sort((a, b) => b.startedAt - a.startedAt)
    })

    // Retornar grupos ordenados por data (mais recente primeiro)
    return Array.from(groups.values()).sort((a, b) => b.date.getTime() - a.date.getTime())
  }, [sessions])

  const displayedDays = dayGroups.slice(0, visibleDays)
  const hasMoreDays = dayGroups.length > visibleDays

  const toggleDay = (dateKey: string) => {
    setExpandedDays((prev) => {
      const next = new Set(prev)
      if (next.has(dateKey)) {
        next.delete(dateKey)
      } else {
        next.add(dateKey)
      }
      return next
    })
  }

  const toggleSession = (sessionId: string) => {
    setExpandedSessions((prev) => {
      const next = new Set(prev)
      if (next.has(sessionId)) {
        next.delete(sessionId)
      } else {
        next.add(sessionId)
      }
      return next
    })
  }

  const loadMoreDays = () => {
    setVisibleDays((prev) => prev + DAYS_PER_PAGE)
  }

  // Não mostrar se não há histórico
  if (!chatHistory || chatHistory.sessions.length === 0) {
    return null
  }

  return (
    <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
      <CardContent className="space-y-4 px-4 pb-6">
        {/* Header */}
        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 pb-4">
          <div>
            <h3 className="text-base font-semibold text-neutral-900">Histórico de chat</h3>
            <p className="text-sm text-neutral-500">
              {chatHistory.sessions.length} {chatHistory.sessions.length === 1 ? "sessão" : "sessões"} - {chatHistory.totalMessages} mensagens
            </p>
          </div>
        </div>

        {/* Grupos por dia */}
        <div className="space-y-2">
          {displayedDays.map((dayGroup) => (
            <DayGroupCard
              key={dayGroup.dateKey}
              dayGroup={dayGroup}
              isExpanded={expandedDays.has(dayGroup.dateKey)}
              onToggle={() => toggleDay(dayGroup.dateKey)}
              expandedSessions={expandedSessions}
              onToggleSession={toggleSession}
            />
          ))}
        </div>

        {/* Carregar mais dias */}
        {hasMoreDays && (
          <div className="text-center pt-2">
            <Button variant="ghost" size="sm" onClick={loadMoreDays}>
              Carregar mais ({dayGroups.length - visibleDays} dias restantes)
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  )
}
