import React from 'react';
import { IProgress } from './types';
import { CircleWrapper, CircleText } from './style';

function add(prev: number, next: number) {
    if (!next) return prev;
    return prev + next;
}

const Circle: React.FC<IProgress> = ({ current, width = 120, height = 4, colors, status = 'normal', children }) => {
    const currents = typeof current === 'number' ? [current] : current;

    while (currents.length > colors!.length) {
        colors = [...colors!, ...colors!];
    }

    const total = currents.reduce(add);
    if (total >= 100) status = 'success';

    const totalPathLen = parseFloat((2 * Math.PI * 47).toFixed(2));
    const pathLens: string[] = [];
    const offsets: number[] = [];
    let prevOffset = 0;
    currents.forEach(current => {
        const percent = ((totalPathLen * current) / total).toFixed(2);
        pathLens.push(percent);
        offsets.push(prevOffset);
        prevOffset += parseFloat(percent);
    });

    const style = {
        transition:
            'stroke-dashoffset 0.3s ease 0s, stroke-dasharray 0.3s ease 0s, stroke 0.3s ease 0s, stroke-width 0.06s ease 0.3s',
    };

    return (
        <div className="progress-wrapper">
            <CircleWrapper width={width} height={width}>
                <svg className="progress-circle " viewBox="0 0 100 100">
                    <path
                        d="M 50,50  m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94"
                        stroke="#E8E8E8"
                        strokeLinecap="butt"
                        strokeWidth={height}
                        fillOpacity="0"
                        strokeDasharray={`${totalPathLen}px, ${totalPathLen}px"`}
                        style={style}
                    />
                    {pathLens.map((pathLen, index) => {
                        return (
                            <path
                                key={index}
                                d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94"
                                stroke={colors![index]}
                                strokeLinecap="butt"
                                strokeWidth={height}
                                fillOpacity="0"
                                strokeDasharray={`${pathLen}px, ${totalPathLen}px`}
                                strokeDashoffset={`-${offsets[index]}px`}
                                style={style}
                            />
                        );
                    })}
                </svg>
                <CircleText>
                    {children ? (
                        children
                    ) : (
                        <span title={`${currents[0]}%`} style={{ fontSize: 24 }}>{`${currents[0]}%`}</span>
                    )}
                </CircleText>
            </CircleWrapper>
        </div>
    );
};

export default React.memo(Circle);
