import React, {CSSProperties, FC, useEffect, useId, useMemo, useRef} from "react";
import classNames from "classnames";

export interface EditHintTextStripProps {
    label: string;
    className?: string;
    textClassName?: string;
    repeatCount?: number;
    inset?: number;
    cornerRadius?: number;
    textStyle?: CSSProperties;
}

export const EditHintTextStrip: FC<EditHintTextStripProps> = ({
    label,
    className,
    textClassName,
    repeatCount = 24,
    inset = 8,
    cornerRadius = 24,
    textStyle,
}) => {
    const svgRef = useRef<SVGSVGElement | null>(null)
    const pathRef = useRef<SVGPathElement | null>(null)
    const rawPathId = useId()
    const pathId = useMemo(
        () => `edit-hint-path-${rawPathId}`.replace(/[^a-zA-Z0-9_-]/g, '-'),
        [rawPathId]
    )
    const text = useMemo(() => `${label} - `.repeat(repeatCount), [label, repeatCount])

    useEffect(() => {
        const svg = svgRef.current
        const path = pathRef.current

        if (!svg || !path) {
            return
        }

        const updatePath = () => {
            const width = Math.max(0, svg.clientWidth)
            const height = Math.max(0, svg.clientHeight)

            if (!width || !height) {
                return
            }

            const left = inset
            const top = inset
            const right = width - inset
            const bottom = height - inset

            path.setAttribute(
                'd',
                `M ${left + cornerRadius} ${top} H ${right - cornerRadius} A ${cornerRadius} ${cornerRadius} 0 0 1 ${right} ${top + cornerRadius} V ${bottom - cornerRadius} A ${cornerRadius} ${cornerRadius} 0 0 1 ${right - cornerRadius} ${bottom} H ${left + cornerRadius} A ${cornerRadius} ${cornerRadius} 0 0 1 ${left} ${bottom - cornerRadius} V ${top + cornerRadius} A ${cornerRadius} ${cornerRadius} 0 0 1 ${left + cornerRadius} ${top} Z`
            )
        }

        updatePath()

        if (typeof ResizeObserver === 'undefined') {
            return
        }

        const resizeObserver = new ResizeObserver(updatePath)
        resizeObserver.observe(svg)

        return () => {
            resizeObserver.disconnect()
        }
    }, [cornerRadius, inset])

    return <svg
        ref={svgRef}
        aria-hidden={true}
        className={classNames('absolute overflow-visible pointer-events-none', className)}
    >
        <defs>
            <path ref={pathRef} id={pathId}/>
        </defs>
        <text
            fill="currentColor"
            style={{fontSize: 10, letterSpacing: '2px', fontWeight: 500, ...textStyle}}
            className={classNames("text-gray-400", textClassName)}
        >
            <textPath href={`#${pathId}`}>
                {text}
            </textPath>
        </text>
    </svg>
}
