import { Skeleton } from "primereact/skeleton";
import { OSLabel } from "../label";
import { resolveIcon } from "../../internal/helpers/resolveIcon";
import { OSChipProps } from "./props";
import { CSSProperties, useRef } from "react";
import { Tooltip } from "primereact/tooltip";

/** 
 * Handle rendering of chip item.
 * Stylized form of OSLabel, with integrated loading state.
 */
export function OSChip({
    colour,
    label,
    className,
    leadingIcon,
    trailingIcon,
    onClick,
    loading,
    link,
    backgroundColour,
    borderColour,
    style,
    tooltip,
    tooltipOptions,
    ...props
}: OSChipProps) {

    const elementRef = useRef<any>(null);

    const styles: CSSProperties = { ...style };
    leadingIcon = resolveIcon(leadingIcon)!;
    trailingIcon = resolveIcon(trailingIcon);

    if (backgroundColour) {
        styles.backgroundColor = backgroundColour;
    }

    return (<div ref={elementRef} className={["os-chip", "w-min", 'flex', 'place-content-center', className].join(" ")}

        onClick={onClick}
        style={{
            ...styles,
            borderColor: borderColour ?? colour ?? "transparent"
        }}>
        {loading
            ? <Skeleton />
            : <OSLabel {...props}
                colour={colour}
                label={label}
                className={[(onClick && "select-none"), className].join(" ")}
                inline
                leadingIcon={leadingIcon && { ...leadingIcon, colour: leadingIcon.colour ?? colour }}
                trailingIcon={trailingIcon && { ...trailingIcon, colour: trailingIcon.colour ?? colour }}
            />}
        {tooltip && (elementRef !== null) && <Tooltip target={elementRef as React.RefObject<HTMLElement>} {...tooltipOptions}>{tooltip}</Tooltip>}
    </div>
    );
}