import React, { useEffect, useRef, useState } from 'react';
import { Tooltip } from '@theorchard/suite-components';

export interface RunTimerTooltipProps {
    children: React.ReactNode;
    avgRunTime: number;
    p95RunningTime: number;
    tooltipLocation?: 'top' | 'right' | 'bottom' | 'left';
    testId?: string;
    onProgress?: (progress: number) => void;
}

export const RunTimerTooltip: React.FC<RunTimerTooltipProps> = ({
    children,
    avgRunTime,
    p95RunningTime,
    tooltipLocation = 'top',
    testId = 'RunTimerTooltip',
    onProgress,
}) => {
    const [elapsed, setElapsed] = useState(0);
    const startRef = useRef<number | null>(null);
    const rafRef = useRef<number | null>(null);

    useEffect(() => {
        const tick = (t: number) => {
            if (startRef.current == null) startRef.current = t;
            const ms = t - startRef.current;
            setElapsed(ms / 1000);
            rafRef.current = requestAnimationFrame(tick);
        };
        rafRef.current = requestAnimationFrame(tick);
        return () => {
            if (rafRef.current) cancelAnimationFrame(rafRef.current);
        };
    }, []);

    useEffect(() => {
        if (elapsed && onProgress) {
            onProgress(elapsed);
        }
    }, [elapsed]);

    const tooltipMessage = (
        <div>
            This process has been running for {elapsed.toFixed(0)}s.
            <br />
            It usually takes between {avgRunTime.toFixed(0)}s and{' '}
            {p95RunningTime.toFixed(0)}s to complete.
        </div>
    );

    return (
        <Tooltip
            message={tooltipMessage}
            placement={tooltipLocation}
            id="RunTimerTooltip"
            testId={testId}
        >
            {children}
        </Tooltip>
    );
};

export default RunTimerTooltip;
