"use client"

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

type InspectionActionsProps = {
    inspectionId: string
    status?: string
    onStatusChange?: () => void
}

const STATUS_TRANSITIONS: Record<string, { next: string; label: string; icon: typeof Play }> = {
    open: { next: "in_progress", label: "Start Inspection", icon: Play },
    in_progress: { next: "completed", label: "Mark Completed", icon: CheckCircle2 },
}

export function InspectionActions({ inspectionId, status, onStatusChange }: InspectionActionsProps) {
    const api = useAuthApi()
    const router = useRouter()

    const handleEdit = () => {
        router.push(`/sales/inspections/${inspectionId}/edit`)
    }

    const handleDelete = async () => {
        const promise = api.inspections.destroy(inspectionId)
        toast.promise(promise, {
            loading: "Deleting inspection...",
            success: "Inspection deleted successfully",
            error: "Failed to delete inspection",
        })
        await promise
        router.push("/sales/inspections")
    }

    const handleStatusChange = async (newStatus: string) => {
        const promise = api.inspections.changeStatus({
            status: newStatus,
        } as never)
        toast.promise(promise, {
            loading: "Updating status...",
            success: "Status updated successfully",
            error: "Failed to update status",
        })
        await promise
        onStatusChange?.()
        router.refresh()
    }

    const transition = status ? STATUS_TRANSITIONS[status] : undefined

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon">
                    <Ellipsis className="size-4" />
                </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={handleEdit}>
                    <Pencil className="size-4" />
                    Edit
                </DropdownMenuItem>
                {transition && (
                    <DropdownMenuItem onClick={() => handleStatusChange(transition.next)}>
                        <transition.icon className="size-4" />
                        {transition.label}
                    </DropdownMenuItem>
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem variant="destructive" onClick={handleDelete}>
                    <Trash2 className="size-4" />
                    Delete
                </DropdownMenuItem>
            </DropdownMenuContent>
        </DropdownMenu>
    )
}
