import { ReactNode } from "react";
import { CmdbItem } from "../store/cmdbSlice/thunks";
import { getFirstEntryValue } from "../utils";
import { Box } from "@mui/material";

const Dim = ({ children }: { children: ReactNode }) => (
    <Box component="span" sx={{ '&&': { color: '#8C8D8E !important' } }}>
        {children}
    </Box>
);

const formatClassName = (name: string) : ReactNode => {
    if (!name) return null;
    const hasNamespace = name.includes(':');
    if (hasNamespace) {
        return name;
    }
    return <><Dim>data:</Dim>{name}</>;
};

const formatVariableName = (item: CmdbItem) : ReactNode => {
    const name = item?.name;
    if (!name) return null;

    const valueSuffix = ` = ${JSON.stringify(getFirstEntryValue(item) ?? '')}`;
    const hasNamespace = name.includes(':');
    const hasBundle = name.includes('.');

    let prefix;

    if (!hasNamespace && !hasBundle) {
        prefix = <Dim>data:variables.</Dim>;
    } else if (!hasNamespace && hasBundle) {
        prefix = <Dim>data:</Dim>;
    }

    return (
        <>
            {prefix}
            {name}
            {valueSuffix}
        </>
    );
};

const CmdbItemPreviewFormatter = (item: CmdbItem) : ReactNode => {
    const typePreviewValues = {
        variable: formatVariableName(item),
        inventory: `${item.name}: ${getFirstEntryValue(item) ?? ''}`,
        class: formatClassName(item?.name),
        default: item.name
    };

    return typePreviewValues[item.type] || typePreviewValues.default;
};

export default CmdbItemPreviewFormatter;
