"use client"

import { useMemo, useState } from "react"
import { usePaginatedQuery } from "convex/react"
import { toast } from "sonner"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { DialogClose, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

type AutomationRunRow = {
  id: Id<"ticketAutomationRuns">
  createdAt: number
  status: "SUCCESS" | "SKIPPED" | "ERROR"
  matched: boolean
  eventType: string
  error: string | null
  actionsApplied: Array<{ type: string; details?: Record<string, unknown> }> | null
  ticket: { id: Id<"tickets">; reference: number; subject: string } | null
  automation: { id: Id<"ticketAutomations">; name: string } | null
}

const EVENT_LABELS: Record<string, string> = {
  TICKET_CREATED: "Abertura",
  STATUS_CHANGED: "Status",
  PRIORITY_CHANGED: "Prioridade",
  QUEUE_CHANGED: "Fila",
  COMMENT_ADDED: "Comentário",
  TICKET_RESOLVED: "Finalização",
}

function formatDateTime(timestamp: number) {
  const date = new Date(timestamp)
  return {
    date: date.toLocaleDateString("pt-BR"),
    time: date.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit", second: "2-digit" }),
  }
}

function statusBadge(status: AutomationRunRow["status"]) {
  if (status === "SUCCESS") return { label: "Sucesso", variant: "secondary" as const }
  if (status === "SKIPPED") return { label: "Ignorada", variant: "outline" as const }
  return { label: "Erro", variant: "destructive" as const }
}

export function AutomationRunsDialog({
  open,
  automationId,
  automationName,
  onClose,
}: {
  open: boolean
  automationId: Id<"ticketAutomations"> | null
  automationName: string | null
  onClose: () => void
}) {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

  const [statusFilter, setStatusFilter] = useState<"all" | "SUCCESS" | "SKIPPED" | "ERROR">("all")

  const args = useMemo(() => {
    if (!open) return "skip" as const
    if (!convexUserId) return "skip" as const
    if (!automationId) return "skip" as const
    return {
      tenantId,
      viewerId: convexUserId as Id<"users">,
      automationId,
      status: statusFilter === "all" ? undefined : statusFilter,
    }
  }, [open, convexUserId, automationId, tenantId, statusFilter])

  const { results, status, loadMore } = usePaginatedQuery(api.automations.listRunsPaginated, args, {
    initialNumItems: 20,
  })

  const isLoadingFirstPage = status === "LoadingFirstPage"
  const isLoadingMore = status === "LoadingMore"
  const canLoadMore = status === "CanLoadMore"

  const rows = (results ?? []) as unknown as AutomationRunRow[]

  return (
    <DialogContent className="max-w-6xl">
      <DialogHeader className="gap-4 pb-2">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="space-y-1">
            <DialogTitle>Histórico de execuções</DialogTitle>
            <DialogDescription className="sr-only">
              Veja as execuções recentes da automação, com status, evento e ticket relacionado.
            </DialogDescription>
            {automationName ? (
              <p className="text-sm text-neutral-600">{automationName}</p>
            ) : null}
          </div>
          <div className="flex items-center gap-2">
            <Select value={statusFilter} onValueChange={(value) => setStatusFilter(value as typeof statusFilter)}>
              <SelectTrigger className="w-[160px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent className="rounded-xl">
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="SUCCESS">Sucesso</SelectItem>
                <SelectItem value="SKIPPED">Ignorada</SelectItem>
                <SelectItem value="ERROR">Erro</SelectItem>
              </SelectContent>
            </Select>
            <DialogClose asChild>
              <Button type="button" variant="outline" onClick={onClose}>
                Fechar
              </Button>
            </DialogClose>
          </div>
        </div>
      </DialogHeader>

      <div className="space-y-3">
        <div className="rounded-3xl border border-slate-200 bg-white/90 shadow-sm overflow-hidden">
          <Table className="w-full table-fixed">
            <colgroup>
              <col style={{ width: "16%" }} />
              <col style={{ width: "22%" }} />
              <col style={{ width: "12%" }} />
              <col style={{ width: "14%" }} />
              <col style={{ width: "10%" }} />
              <col style={{ width: "26%" }} />
            </colgroup>
            <TableHeader className="bg-slate-100/80">
              <TableRow className="bg-transparent text-[11px] uppercase tracking-wide text-neutral-600 hover:bg-transparent">
                <TableHead className="px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                  Data
                </TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                  Ticket
                </TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                  Evento
                </TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                  Resultado
                </TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                  Ações
                </TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                  Detalhes
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoadingFirstPage ? (
                Array.from({ length: 6 }).map((_, i) => (
                  <TableRow key={`skeleton-${i}`} className="animate-pulse">
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-28" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-44" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-20" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-8 w-24 rounded-full" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-10" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-56" /></TableCell>
                  </TableRow>
                ))
              ) : rows.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="py-10 text-center text-sm text-neutral-500">
                    Nenhuma execução encontrada.
                  </TableCell>
                </TableRow>
              ) : (
                rows.map((run) => {
                  const badge = statusBadge(run.status)
                  const eventLabel = EVENT_LABELS[run.eventType] ?? run.eventType
                  const actionsCount = run.actionsApplied?.length ?? 0
                  const actionsLabel =
                    actionsCount === 1 ? "Aplicou 1 ação" : `Aplicou ${actionsCount} ações`
                  const createdAtLabel = formatDateTime(run.createdAt)
                  const details =
                    run.status === "ERROR"
                      ? run.error ?? "Erro desconhecido"
                      : run.status === "SKIPPED"
                        ? run.matched
                          ? "Ignorada"
                          : "Condições não atendidas"
                        : actionsCount > 0
                          ? actionsLabel
                          : "Sem alterações"

                  return (
                    <TableRow key={run.id} className="transition-colors hover:bg-cyan-50/30">
                      <TableCell className="text-center text-sm text-neutral-700">
                        <div className="space-y-0.5">
                          <div className="font-medium text-neutral-900">{createdAtLabel.date}</div>
                          <div className="text-xs text-neutral-600">{createdAtLabel.time}</div>
                        </div>
                      </TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">
                        {run.ticket ? (
                          <div className="space-y-0.5">
                            <div className="font-semibold text-neutral-900">#{run.ticket.reference}</div>
                            <div className="truncate text-xs text-neutral-600" title={run.ticket.subject}>
                              {run.ticket.subject || "—"}
                            </div>
                          </div>
                        ) : (
                          "—"
                        )}
                      </TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">
                        <span className="truncate" title={eventLabel}>
                          {eventLabel}
                        </span>
                      </TableCell>
                      <TableCell className="text-center">
                        <Badge variant={badge.variant} className="rounded-full">
                          {badge.label}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">{actionsCount}</TableCell>
                      <TableCell className="text-center text-sm text-neutral-700 truncate" title={details}>
                        {details}
                      </TableCell>
                    </TableRow>
                  )
                })
              )}
            </TableBody>
          </Table>
        </div>

        {canLoadMore ? (
          <div className="flex justify-center">
            <Button
              type="button"
              variant="outline"
              onClick={() => {
                try {
                  loadMore(20)
                } catch (error) {
                  toast.error(error instanceof Error ? error.message : "Falha ao carregar mais")
                }
              }}
              disabled={isLoadingMore}
              className="rounded-full"
            >
              {isLoadingMore ? "Carregando..." : "Carregar mais"}
            </Button>
          </div>
        ) : null}
      </div>
    </DialogContent>
  )
}
