"use client"

import { useMemo, useState } from "react"
import { useMutation, useQuery } from "convex/react"
import { AlertTriangle, History, MoreHorizontal, Pencil, Plus, Trash2 } from "lucide-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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Switch } from "@/components/ui/switch"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

import { AutomationEditorDialog } from "@/components/automations/automation-editor-dialog"
import { AutomationRunsDialog } from "@/components/automations/automation-runs-dialog"

type AutomationRow = {
  id: Id<"ticketAutomations">
  name: string
  enabled: boolean
  trigger: string
  timing: string
  delayMs: number | null
  conditions: unknown | null
  actions: unknown[]
  runCount: number
  lastRunAt: number | null
  updatedAt: number
}

const TRIGGER_LABELS: Record<string, string> = {
  TICKET_CREATED: "Abertura",
  STATUS_CHANGED: "Alteração de status",
  PRIORITY_CHANGED: "Alteração de prioridade",
  QUEUE_CHANGED: "Alteração de fila",
  COMMENT_ADDED: "Inclusão de comentário",
  TICKET_RESOLVED: "Finalização",
}

function triggerLabel(trigger: string) {
  return TRIGGER_LABELS[trigger] ?? trigger
}

function formatLastRun(timestamp: number | null) {
  if (!timestamp) return null
  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 formatConditionsSummary(conditions: unknown | null) {
  if (!conditions || typeof conditions !== "object" || Array.isArray(conditions)) return "—"
  const group = conditions as { op?: unknown; conditions?: unknown }
  const list = Array.isArray(group.conditions) ? group.conditions : []
  if (list.length === 0) return "—"
  const op = typeof group.op === "string" ? group.op.toUpperCase() : "AND"
  const opLabel = op === "OR" ? "OU" : "E"
  return `${list.length} (${opLabel})`
}

export function AutomationsManager() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

  const [queryText, setQueryText] = useState("")
  const [triggerFilter, setTriggerFilter] = useState<string>("all")
  const [statusFilter, setStatusFilter] = useState<string>("all")

  const [editorOpen, setEditorOpen] = useState(false)
  const [editing, setEditing] = useState<AutomationRow | null>(null)
  const [runsOpen, setRunsOpen] = useState(false)
  const [runsAutomation, setRunsAutomation] = useState<AutomationRow | null>(null)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [deletingAutomation, setDeletingAutomation] = useState<AutomationRow | null>(null)
  const [deleteLoading, setDeleteLoading] = useState(false)

  const list = useQuery(
    api.automations.list,
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as AutomationRow[] | undefined

  const toggleEnabled = useMutation(api.automations.toggleEnabled)
  const removeAutomation = useMutation(api.automations.remove)

  const filtered = useMemo(() => {
    const base = list ?? []
    const q = queryText.trim().toLowerCase()
    return base
      .filter((item) => {
        if (triggerFilter !== "all" && item.trigger !== triggerFilter) return false
        if (statusFilter === "active" && !item.enabled) return false
        if (statusFilter === "inactive" && item.enabled) return false
        if (q && !item.name.toLowerCase().includes(q)) return false
        return true
      })
      .sort((a, b) => b.updatedAt - a.updatedAt)
  }, [list, queryText, triggerFilter, statusFilter])

  const handleNew = () => {
    setEditing(null)
    setEditorOpen(true)
  }

  const handleEdit = (row: AutomationRow) => {
    setEditing(row)
    setEditorOpen(true)
  }

  const handleOpenRuns = (row: AutomationRow) => {
    setRunsAutomation(row)
    setRunsOpen(true)
  }

  const handleToggle = async (row: AutomationRow, nextEnabled: boolean) => {
    if (!convexUserId) return
    try {
      await toggleEnabled({
        tenantId,
        viewerId: convexUserId as Id<"users">,
        automationId: row.id,
        enabled: nextEnabled,
      })
      toast.success(nextEnabled ? "Automação ativada" : "Automação desativada")
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Falha ao atualizar automação")
    }
  }

  const handleDeleteClick = (row: AutomationRow) => {
    setDeletingAutomation(row)
    setDeleteOpen(true)
  }

  const handleDeleteConfirm = async () => {
    if (!convexUserId || !deletingAutomation) return
    setDeleteLoading(true)
    try {
      await removeAutomation({
        tenantId,
        viewerId: convexUserId as Id<"users">,
        automationId: deletingAutomation.id,
      })
      toast.success("Automação excluída")
      setDeleteOpen(false)
      setDeletingAutomation(null)
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Falha ao excluir automação")
    } finally {
      setDeleteLoading(false)
    }
  }

  return (
    <Card className="border-slate-200">
      <CardHeader className="space-y-4">
        <div>
          <CardTitle className="text-lg font-semibold text-neutral-900">Automações</CardTitle>
          <CardDescription className="mt-1 text-neutral-600">
            Crie gatilhos para executar ações automáticas nos tickets.
          </CardDescription>
        </div>
        <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">
            <Input
              value={queryText}
              onChange={(e) => setQueryText(e.target.value)}
              placeholder="Buscar automação..."
              className="h-8 w-full text-sm sm:w-56"
            />
            <Select value={triggerFilter} onValueChange={setTriggerFilter}>
              <SelectTrigger size="sm" className="w-full sm:w-48">
                <span className="truncate">
                  <span className="text-neutral-500">Quando:</span> <SelectValue />
                </span>
              </SelectTrigger>
              <SelectContent className="rounded-xl">
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="TICKET_CREATED">Abertura</SelectItem>
                <SelectItem value="STATUS_CHANGED">Status</SelectItem>
                <SelectItem value="PRIORITY_CHANGED">Prioridade</SelectItem>
                <SelectItem value="QUEUE_CHANGED">Fila</SelectItem>
                <SelectItem value="COMMENT_ADDED">Comentário</SelectItem>
                <SelectItem value="TICKET_RESOLVED">Finalização</SelectItem>
              </SelectContent>
            </Select>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger size="sm" className="w-full sm:w-40">
                <span className="truncate">
                  <span className="text-neutral-500">Ativação:</span> <SelectValue />
                </span>
              </SelectTrigger>
              <SelectContent className="rounded-xl">
                <SelectItem value="all">Todos</SelectItem>
                <SelectItem value="active">Ativas</SelectItem>
                <SelectItem value="inactive">Inativas</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <Dialog open={editorOpen} onOpenChange={setEditorOpen}>
            <DialogTrigger asChild>
              <Button size="sm" onClick={handleNew} className="gap-2">
                <Plus className="size-4" />
                Nova automação
              </Button>
            </DialogTrigger>
            <AutomationEditorDialog
              automation={editing}
              onClose={() => setEditorOpen(false)}
            />
          </Dialog>
        </div>
      </CardHeader>
      <CardContent>
        <Dialog
          open={runsOpen}
          onOpenChange={(next) => {
            setRunsOpen(next)
            if (!next) {
              setRunsAutomation(null)
            }
          }}
        >
          <AutomationRunsDialog
            open={runsOpen}
            automationId={runsAutomation?.id ?? null}
            automationName={runsAutomation?.name ?? null}
            onClose={() => setRunsOpen(false)}
          />
        </Dialog>

        {!list ? (
          <div className="space-y-2">
            {Array.from({ length: 6 }).map((_, i) => (
              <Skeleton key={i} className="h-12 w-full rounded-lg" />
            ))}
          </div>
        ) : filtered.length === 0 ? (
          <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
            Nenhuma automação cadastrada.
          </p>
        ) : (
          <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: "20%" }} />
                <col style={{ width: "18%" }} />
                <col style={{ width: "10%" }} />
                <col style={{ width: "7%" }} />
                <col style={{ width: "10%" }} />
                <col style={{ width: "14%" }} />
                <col style={{ width: "14%" }} />
                <col style={{ width: "7%" }} />
              </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">
                    Nome
                  </TableHead>
                  <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                    Quando
                  </TableHead>
                  <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                    Condiçõ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">
                    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">
                    Execuçõ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">
                    Última
                  </TableHead>
                  <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">
                    Status
                  </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>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filtered.map((row) => {
                  const lastRun = formatLastRun(row.lastRunAt)
                  return (
                    <TableRow key={row.id} className="transition-colors hover:bg-cyan-50/30">
                      <TableCell className="text-center font-semibold text-neutral-900 truncate" title={row.name}>
                        {row.name}
                      </TableCell>
                      <TableCell className="text-center px-2">
                        <div className="flex items-center justify-center gap-2">
                          <Badge variant="secondary" className="rounded-full px-3 max-w-full truncate">
                            {triggerLabel(row.trigger)}
                          </Badge>
                          {row.timing === "DELAYED" && row.delayMs ? (
                            <Badge variant="outline" className="rounded-full px-2.5">
                              +{Math.round(row.delayMs / 60000)}m
                            </Badge>
                          ) : null}
                        </div>
                      </TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">
                        {formatConditionsSummary(row.conditions)}
                      </TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">{row.actions?.length ?? 0}</TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">{row.runCount ?? 0}</TableCell>
                      <TableCell className="text-center text-sm text-neutral-700">
                        {lastRun ? (
                          <div className="space-y-0.5">
                            <div className="font-medium text-neutral-900">{lastRun.date}</div>
                            <div className="text-xs text-neutral-600">{lastRun.time}</div>
                          </div>
                        ) : (
                          "—"
                        )}
                      </TableCell>
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-2">
                          <Switch
                            checked={row.enabled}
                            onCheckedChange={(checked) => handleToggle(row, checked)}
                            className="data-[state=checked]:bg-black data-[state=unchecked]:bg-slate-300"
                          />
                          <span className="text-xs font-medium text-neutral-700">{row.enabled ? "Ativa" : "Inativa"}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-center">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-9 w-9 rounded-full">
                              <MoreHorizontal className="size-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="rounded-xl">
                            <DropdownMenuItem onClick={() => handleOpenRuns(row)} className="gap-2">
                              <History className="size-4" />
                              Histórico
                            </DropdownMenuItem>
                            <DropdownMenuItem onClick={() => handleEdit(row)} className="gap-2">
                              <Pencil className="size-4" />
                              Editar
                            </DropdownMenuItem>
                            <DropdownMenuItem variant="destructive" onClick={() => handleDeleteClick(row)} className="gap-2">
                              <Trash2 className="size-4" />
                              Excluir
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>

      {/* Modal de confirmação de exclusão */}
      <Dialog open={deleteOpen} onOpenChange={(open) => {
        setDeleteOpen(open)
        if (!open) setDeletingAutomation(null)
      }}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-destructive">
              <AlertTriangle className="size-5" /> Excluir automação
            </DialogTitle>
            <DialogDescription>
              Esta ação é permanente e removerá a automação <span className="font-semibold text-neutral-700">&quot;{deletingAutomation?.name}&quot;</span> e todo o seu histórico de execuções.
            </DialogDescription>
          </DialogHeader>
          <div className="flex justify-end gap-2 pt-2">
            <Button variant="outline" onClick={() => setDeleteOpen(false)} disabled={deleteLoading}>
              Cancelar
            </Button>
            <Button variant="destructive" onClick={handleDeleteConfirm} disabled={deleteLoading} className="gap-2">
              {deleteLoading ? "Excluindo..." : (<><Trash2 className="size-4" /> Excluir</>)}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </Card>
  )
}
