"use client"

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

interface UseDocumentShareOptions {
    onSuccess?: (result: DocumentShareResponse) => void
    onError?: (error: Error) => void
}

export function useDocumentShare(type: DocumentShareType, id: string | number, options?: UseDocumentShareOptions) {
    const api = useAuthApi()
    const [isSharing, setIsSharing] = useState(false)

    const shareEmail = async (input: { email: string; message?: string }) => {
        setIsSharing(true)
        try {
            const result = await api.documentShare.share({
                document_type: type,
                document_id: id,
                channel: "email",
                email: input.email,
                message: input.message,
            })
            toast.success("Email sent. Link expires in 24 hours.")
            options?.onSuccess?.(result)
            return result
        } catch (error) {
            toast.error("Failed to send email")
            options?.onError?.(error as Error)
            throw error
        } finally {
            setIsSharing(false)
        }
    }

    const shareWhatsapp = async (input: { phone?: string; message?: string }) => {
        setIsSharing(true)
        try {
            const result = await api.documentShare.share({
                document_type: type,
                document_id: id,
                channel: "link",
                phone: input.phone,
                message: input.message,
            })
            window.open(result.whatsapp_url, "_blank", "noopener,noreferrer")
            toast.success("Share link ready. Expires in 24 hours.")
            options?.onSuccess?.(result)
            return result
        } catch (error) {
            toast.error("Failed to create share link")
            options?.onError?.(error as Error)
            throw error
        } finally {
            setIsSharing(false)
        }
    }

    return { shareEmail, shareWhatsapp, isSharing }
}
