import { Fragment } from "react";

import { isUrl } from "@devowl-wp/react-utils";
import { extendCommonGroupsStylesheet, extendCommonStylesheet } from "@devowl-wp/web-cookie-banner";

import { useStylesheet } from "../../../contexts/stylesheet.js";
import { useBannerOrBlocker } from "../../../hooks/useBannerOrBlocker.js";

import type { FC, PropsWithChildren, ReactNode } from "react";

const CookieProperty: FC<
    PropsWithChildren<{
        label?: string;
        value?: string | ReactNode;
        printValueAs?: "boolean" | "phone" | "mail" | "empty";
        monospace?: boolean;
    }>
> = ({ label, value, children, printValueAs, monospace }) => {
    const stylesheet = useStylesheet();
    const { Link, CookieProperty } = stylesheet
        .extend(...extendCommonStylesheet)
        .extend(...extendCommonGroupsStylesheet);
    const banner = useBannerOrBlocker();
    const {
        i18n: { yes, no },
    } = banner;
    const isValueUrl = typeof value === "string" && value.startsWith("http") && isUrl(value);

    let useValue = isValueUrl ? (
        <Link href={value as string} target="_blank" rel="noopener noreferrer">
            {value}
        </Link>
    ) : typeof value === "string" ? (
        printValueAs === "phone" ? (
            <Link target="_blank" href={`tel:${value.replace(/\s+/g, "")}`}>
                {value}
            </Link>
        ) : printValueAs === "mail" ? (
            <Link target="_blank" href={`mailto:${value}`}>
                {value}
            </Link>
        ) : (
            <span dangerouslySetInnerHTML={{ __html: value }} />
        )
    ) : (
        value
    );

    if (printValueAs === "boolean") {
        useValue = useValue ? yes : no;
    }

    return value || value === false || printValueAs === "empty" ? (
        <Fragment>
            <CookieProperty>
                {label && <strong>{label}:&nbsp;</strong>}
                <span role="presentation" style={{ fontFamily: monospace ? "monospace" : undefined }}>
                    {useValue}
                </span>
            </CookieProperty>
            <CookieProperty>{!!children && <div>{children}</div>}</CookieProperty>
        </Fragment>
    ) : null;
};

export { CookieProperty };
