"use client"

import { useRouter } from "next/navigation"
import { 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"

export function DeleteTicketDialog({ ticketId }: { ticketId: Id<"tickets"> }) {
  const router = useRouter()
  const remove = useMutation(api.tickets.remove)
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)

  async function confirm() {
    setLoading(true)
    toast.loading("Excluindo ticket...", { id: "del" })
    try {
      await remove({ ticketId })
      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-transparent bg-transparent text-[#ef4444] transition hover:border-[#fecaca] hover:bg-[#fee2e2] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#fecaca]/50"
        >
          <Trash2 className="size-4 text-current" />
        </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>
  )
}
