import { Box, Typography } from '@mui/material';
import { useMemo, type ReactNode } from 'react';

const SEGMENTS = 24;
const START_ANGLE = 135;
const SWEEP = 270;

export type GaugeScoreProps = {
    value: number | null | undefined;
    className?: string;
    'aria-label'?: string;
    /** Texto opcional debajo del velocímetro */
    footer?: ReactNode;
    activeColor?: string;
    inactiveColor?: string;
};

function clampScore(value: number | null | undefined): number {
    const n = Number(value ?? 0);
    if (!Number.isFinite(n)) {
        return 0;
    }
    return Math.min(100, Math.max(0, n));
}

function polarToCartesian(cx: number, cy: number, r: number, angleDeg: number) {
    const rad = (angleDeg * Math.PI) / 180;
    return {
        x: cx + r * Math.cos(rad),
        y: cy + r * Math.sin(rad),
    };
}

export default function GaugeScore({
    value,
    className,
    'aria-label': ariaLabel = 'Velocímetro de puntaje',
    footer,
    activeColor = '#00D8FF',
    inactiveColor = '#9ca3af',
}: GaugeScoreProps) {
    const score = clampScore(value);
    const displayValue = value != null && Number.isFinite(Number(value)) ? Math.round(score) : '—';

    const activeSegments = useMemo(
        () => Math.round((score / 100) * SEGMENTS),
        [score],
    );

    const cx = 100;
    const cy = 98;
    const radius = 72;
    const segW = 7;
    const segH = 22;

    return (
        <Box
            className={className}
            role="img"
            aria-label={`${ariaLabel}: ${displayValue}`}
            sx={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                width: '100%',
                minHeight: 160,
            }}
        >
            <Box sx={{ position: 'relative', width: '100%', maxWidth: 220, aspectRatio: '200 / 130' }}>
                <svg
                    viewBox="0 0 200 130"
                    width="100%"
                    height="100%"
                    aria-hidden
                    style={{ display: 'block' }}
                >
                    {Array.from({ length: SEGMENTS }, (_, i) => {
                        const angle = START_ANGLE + (i / (SEGMENTS - 1)) * SWEEP;
                        const { x, y } = polarToCartesian(cx, cy, radius, angle);
                        const isActive = i < activeSegments;
                        return (
                            <rect
                                key={i}
                                x={-segW / 2}
                                y={-segH}
                                width={segW}
                                height={segH}
                                rx={1.5}
                                fill={isActive ? activeColor : inactiveColor}
                                opacity={isActive ? 1 : 0.55}
                                transform={`translate(${x} ${y}) rotate(${angle + 90})`}
                            />
                        );
                    })}
                </svg>
                <Typography
                    component="span"
                    sx={{
                        position: 'absolute',
                        left: '50%',
                        top: '58%',
                        transform: 'translate(-50%, -50%)',
                        fontSize: { xs: '2.4rem', sm: '2.75rem' },
                        fontWeight: 700,
                        fontStyle: 'italic',
                        lineHeight: 1,
                        color: 'text.primary',
                        letterSpacing: '-0.02em',
                        userSelect: 'none',
                    }}
                >
                    {displayValue}%
                </Typography>
            </Box>
            {footer ? (
                <Box sx={{ mt: 1, textAlign: 'center', width: '100%' }}>{footer}</Box>
            ) : null}
        </Box>
    );
}
