import type {SharedValue} from "react-native-reanimated"

import {
    CONTENT_HEIGHT_SNAP_POINT,
    CONTENT_HEIGHT_WITH_OVERLAY_FOOTER_SNAP_POINT,
    type SheetPosition,
    type SheetPositionValue,
} from "../utils/constants"
import {getPercentageValue} from "../utils/get-percentage-value"

export function getSheetPositionValue(value: SheetPosition): SheetPositionValue {
    "worklet"

    return value !== null && typeof value === "object" && "value" in value ? value.get() : value
}

interface UseNormalizedSheetPositionArgs {
    sheetPosition: SheetPosition
    wrapperHeightSharedValue: SharedValue<number | null>
    childrenHeightSharedValue: SharedValue<number | null>
    footerHeightSharedValue: SharedValue<number | null>
}

export function normalizeSheetPosition({
    sheetPosition,
    childrenHeightSharedValue,
    wrapperHeightSharedValue,
    footerHeightSharedValue,
}: UseNormalizedSheetPositionArgs) {
    "worklet"
    const sheetPositionValue = getSheetPositionValue(sheetPosition)

    if (sheetPositionValue === CONTENT_HEIGHT_SNAP_POINT) {
        return childrenHeightSharedValue.get()
    } else if (sheetPositionValue === CONTENT_HEIGHT_WITH_OVERLAY_FOOTER_SNAP_POINT) {
        const childrenHeight = childrenHeightSharedValue.get()
        const footerHeight = footerHeightSharedValue.get()
        return childrenHeight === null || footerHeight === null
            ? null
            : childrenHeight + footerHeight
    } else if (typeof sheetPositionValue === "number") {
        return sheetPositionValue
    } else if (typeof sheetPositionValue === "string" && sheetPositionValue.endsWith("%")) {
        const pv = getPercentageValue(sheetPositionValue)
        if (pv !== null) {
            const wrapperHeight = wrapperHeightSharedValue.get()
            return wrapperHeight === null ? null : pv * wrapperHeight
        }
    } else if (sheetPositionValue === null) {
        return null
    }

    throw new Error(`Malformed SheetPosition in bottom-sheet: ${JSON.stringify(sheetPosition)}.`)
}
