"use client"

import { useState } from "react"
import { useAuthApi } from "../useApi"
import { toast } from "sonner"
import type { DocumentPrintMode, DocumentPrintType } from "@garage/api"

interface UseDocumentPrintOptions {
    onSuccess?: (blob: Blob) => void
    onError?: (error: Error) => void
}

export function useDocumentPrint(options?: UseDocumentPrintOptions) {
    const api = useAuthApi()
    const [isPrinting, setIsPrinting] = useState(false)

    const print = async (
        type: DocumentPrintType,
        id: string | number,
        mode: DocumentPrintMode = "print",
        filename?: string,
    ) => {
        setIsPrinting(true)
        try {
            const blob = await api.documentPrint.print(type, id, mode)

            const url = URL.createObjectURL(blob)

            if (mode === "print") {
                const win = window.open(url, "_blank")
                if (win) {
                    win.addEventListener("load", () => {
                        win.print()
                        URL.revokeObjectURL(url)
                    })
                } else {
                    URL.revokeObjectURL(url)
                }
            } else {
                const a = document.createElement("a")
                a.href = url
                a.download = filename ?? `${type}-${id}.pdf`
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
                URL.revokeObjectURL(url)
            }

            options?.onSuccess?.(blob)
        } catch (error) {
            toast.error("Failed to print document")
            options?.onError?.(error as Error)
        } finally {
            setIsPrinting(false)
        }
    }

    return { print, isPrinting }
}
