"use client"

import { useRouter } from "next/navigation"
import { useMemo, useState } from "react"
import { useMutation } from "convex/react"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogTrigger } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { AlertTriangle, Trash2 } from "lucide-react"
import { toast } from "sonner"

import { useAuth } from "@/lib/auth-client"

export function DeleteTicketDialog({ ticketId }: { ticketId: Id<"tickets"> }) {
  const router = useRouter()
  const remove = useMutation(api.tickets.remove)
  const { convexUserId, isAdmin } = useAuth()
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const viewerId = useMemo(() => (isAdmin && convexUserId ? (convexUserId as Id<"users">) : null), [isAdmin, convexUserId])

  if (!viewerId) {
    return null
  }

  async function confirm() {
    setLoading(true)
    toast.loading("Excluindo ticket...", { id: "del" })
    try {
      if (!viewerId) {
        throw new Error("missing actor")
      }
      await remove({ ticketId, actorId: viewerId })
      toast.success("Ticket excluído.", { id: "del" })
      setOpen(false)
      router.push("/tickets")
    } catch {
      toast.error("Não foi possível excluir o ticket.", { id: "del" })
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          size="icon"
          aria-label="Excluir ticket"
          className="h-9 w-9 rounded-lg border border-rose-300 bg-white text-rose-600 transition hover:bg-rose-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rose-200"
        >
          <Trash2 className="size-4" />
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-destructive">
            <AlertTriangle className="size-5" /> Excluir ticket
          </DialogTitle>
          <DialogDescription>
            Esta ação é permanente e removerá o ticket, comentários e eventos associados. Deseja continuar?
          </DialogDescription>
        </DialogHeader>
        <div className="flex justify-end gap-2 pt-2">
          <Button variant="outline" onClick={() => setOpen(false)}>Cancelar</Button>
          <Button variant="destructive" onClick={confirm} disabled={loading} className="gap-2">
            {loading ? "Excluindo..." : (<><Trash2 className="size-4" /> Excluir</>)}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}
