import Text from '../Text/Text';
import { twMerge } from 'tailwind-merge';

export interface ProgressRingProps {
    /**
     * Colors for the text inside the circle and the circle
     */
    color?: {
        text: string;
        ring: string;
    };
    /**
     * Radius of the circle.
     */
    radius?: number;
    /**
     * Border width opf the progress circle.
     */
    borderWidth?: number;
    /**
     * number from 0-100 for the total progress in %.
     */
    progress?: number;
    /**
     * Main container className for css classes .
     */
    className?: string;
}

const ProgressRing: React.FC<ProgressRingProps> = (props) => {
    const { radius, borderWidth, className, progress, color } = props;

    const initialStyles = 'relative inline-flex justify-center items-center text-3xl';

    const normalizedRadius = radius && borderWidth && radius - borderWidth * 2;
    const circumference = normalizedRadius && normalizedRadius * 2 * Math.PI;
    const strokeDashoffset = circumference && circumference - (progress ? progress / 100 : 0) * circumference;

    const style = {
        transform: 'rotate(-90deg)',
        WebkitTransform: 'rotate(-89.5deg)', // Safari fix
    };

    return (
        <div className={twMerge(`${initialStyles} ${className ? className : ''}`)}>
            <Text className={`absolute leading-none ${color?.text}`}>
                {progress ? progress : 0}
                <span className="absolute right-0">
                    <span className="absolute transform scale-50">%</span>
                </span>
            </Text>
            <svg className={color?.ring} height={radius && radius * 2} width={radius && radius * 2} style={style}>
                <circle
                    stroke="currentColor"
                    className="opacity-30"
                    fill="transparent"
                    strokeWidth={borderWidth}
                    r={normalizedRadius}
                    cx={radius}
                    cy={radius}
                />
                <circle
                    className="text-inherit"
                    stroke={'currentColor'}
                    fill="transparent"
                    strokeWidth={borderWidth}
                    strokeDasharray={circumference + ' ' + circumference}
                    style={{ strokeDashoffset }}
                    r={normalizedRadius}
                    cx={radius}
                    cy={radius}
                />
            </svg>
        </div>
    );
};

ProgressRing.defaultProps = {
    radius: 60,
    borderWidth: 5,
};

ProgressRing.displayName = 'ProgressRing';

export default ProgressRing;
