"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 { useFormDialog } from "@/shared/components/form-dialog"
import { EmployeeForm } from "./employee-form"

type EmployeeActionsProps = {
    employeeId: string
}

export function EmployeeActions({ employeeId }: EmployeeActionsProps) {
    const api = useAuthApi()
    const router = useRouter()
    const editDialog = useFormDialog("employee_edit")

    const handleDelete = async () => {
        await api.employees.destroy(employeeId)
        router.push("/productivity/employees")
    }

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

            <Dialog open={editDialog.isOpen} onOpenChange={(v) => { if (!v) editDialog.close() }}>
                <DialogContent className="min-w-xl">
                    <DialogHeader>
                        <DialogTitle className="text-2xl font-bold">Edit Employee</DialogTitle>
                    </DialogHeader>
                    <ScrollArea className="max-h-[80vh] px-4">
                        <EmployeeForm
                            resourceId={editDialog.resourceId}
                            onSuccess={() => {
                                editDialog.close()
                                router.refresh()
                            }}
                        />
                    </ScrollArea>
                </DialogContent>
            </Dialog>
        </>
    )
}
