"use client"

import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { confirm } from "@/shared/components/confirm-dialog"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { toast } from "sonner"

type PurchaseOrderActionsProps = {
    purchaseOrderId: string
}

export function PurchaseOrderActions({ purchaseOrderId }: PurchaseOrderActionsProps) {
    const api = useAuthApi()
    const router = useRouter()

    const handleDelete = async () => {
        const confirmed = await confirm({
            title: "Delete this purchase order?",
            description: "This action cannot be undone.",
            confirmLabel: "Delete",
            variant: "destructive",
        })
        if (!confirmed) return

        const promise = api.purchaseOrders.destroy(purchaseOrderId)
        toast.promise(promise, {
            loading: "Deleting purchase order...",
            success: "Purchase order deleted",
            error: "Failed to delete purchase order",
        })
        await promise
        router.push("/purchase/purchase-order")
    }

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon">
                    <Ellipsis className="size-4" />
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
                <DropdownMenuItem variant="destructive" onClick={handleDelete}>
                    <Trash2 className="size-4" />
                    Delete
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    )
}
