"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 {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"
import { useState } from "react"
import { EstimateForm } from "./estimate-form"

type EstimateActionsProps = {
    estimateId: string
}

export function EstimateActions({ estimateId }: EstimateActionsProps) {
    const api = useAuthApi()
    const router = useRouter()
    const [editOpen, setEditOpen] = useState(false)

    const handleDelete = async () => {
        await api.estimates.destroy(estimateId)
        router.push("/sales/estimates")
    }

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

            <Dialog open={editOpen} onOpenChange={setEditOpen}>
                <DialogContent className="min-w-xl">
                    <DialogHeader>
                        <DialogTitle className="text-2xl font-bold">Edit Estimate</DialogTitle>
                    </DialogHeader>
                    <ScrollArea className="max-h-[80vh] px-4">
                        <EstimateForm
                            resourceId={estimateId}
                            onSuccess={() => {
                                setEditOpen(false)
                                router.refresh()
                            }}
                        />
                    </ScrollArea>
                </DialogContent>
            </Dialog>
        </>
    )
}
