// components/ui/error-message.tsx
import React from "react"

type ErrorMessageProps = {
    error: unknown
    fallback?: string
}

function getErrorMessage(error: unknown, fallback: string) {
    if (typeof error === "object" && error !== null) {
        const err = error as {
            response?: {
                data?: {
                    error?: string
                }
            }
            message?: string
        }

        // API response error
        if (err.response?.data?.error) {
            return err.response.data.error
        }

        // Generic JS error
        if (err.message) {
            return err.message
        }
    }

    return fallback
}

export function ErrorMessage({
    error,
    fallback = "Something went wrong",
}: ErrorMessageProps) {
    if (!error) return null

    const message = getErrorMessage(error, fallback)

    return (
        <div className="rounded-md border border-red-300 bg-red-50 p-3 text-sm text-red-700">
            {message}
        </div>
    )
}