"use client"

import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { useFormDialog } from "@/shared/components/form-dialog"
import { VehicleForm } from "./vehicle-form"
import { Ellipsis, Pencil, Trash2 } from "lucide-react"

type VehicleActionsProps = {
    vehicleId: string
}

export function VehicleActions({ vehicleId }: VehicleActionsProps) {
    const api = useAuthApi()
    const router = useRouter()
    const editDialog = useFormDialog("vehicle-details-edit")

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

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon">
                    <Ellipsis className="size-4" />
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
                <DropdownMenuItem onSelect={() => editDialog.open(vehicleId)}>
                    <Pencil className="size-4" />
                    Edit
                </DropdownMenuItem>
                <DropdownMenuItem variant="destructive" onClick={handleDelete}>
                    <Trash2 className="size-4" />
                    Delete
                </DropdownMenuItem>
            </DropdownMenuContent>
            <Dialog open={editDialog.isOpen} onOpenChange={(isOpen) => { if (!isOpen) editDialog.close() }}>
                <DialogContent className="min-w-xl lg:min-w-4xl">
                    <DialogHeader>
                        <DialogTitle className="text-2xl font-bold">Vehicle</DialogTitle>
                    </DialogHeader>
                    <ScrollArea className="max-h-[80vh] px-4">
                        <VehicleForm
                        
                            resourceId={editDialog.resourceId}
                            onSuccess={() => {
                                editDialog.close()
                                router.refresh()
                            }}
                        />
                    </ScrollArea>
                </DialogContent>
            </Dialog>
        </DropdownMenu>
    )
}
