"use client"

import { useAuthApi } from "@/shared/useApi"
import { useRouter } from "next/navigation"
import { parseApiError } from "@garage/api"
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,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { Ellipsis, Pencil, Trash2, Play, CheckCircle2, Printer, Share2 } from "lucide-react"
import { useState } from "react"
import { toast } from "sonner"
import { useFormDialog } from "@/shared/components/form-dialog"
import { InspectionForm } from "./inspection-form"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"
import { ShareDocumentDialog } from "@/shared/components/share-document-dialog"

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 editDialog = useFormDialog("inspection-details-edit")
    const { print, isPrinting } = useDocumentPrint()
    const [shareOpen, setShareOpen] = useState(false)

    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 loadingToast = toast.loading("Updating status...")
        try {
            await api.inspections.changeStatus({
                id: Number(inspectionId),
                status: newStatus,
            } as never)
            toast.success("Status updated successfully", { id: loadingToast })
            onStatusChange?.()
            router.refresh()
        } catch (e) {
            toast.error(parseApiError(e, "Failed to update status"), { id: loadingToast })
        }
    }

    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={() => editDialog.open(inspectionId)}>
                        <Pencil className="size-4" />
                        Edit
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => print("inspection", inspectionId, "print")} disabled={isPrinting}>
                        <Printer className="size-4" />
                        {isPrinting ? "Printing..." : "Print"}
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => setShareOpen(true)}>
                        <Share2 className="size-4" />
                        Share
                    </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>

            <ShareDocumentDialog type="inspection" id={inspectionId} open={shareOpen} onOpenChange={setShareOpen} />

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