import { useMemo } from 'react';
import {
    Bar,
    BarChart,
    CartesianGrid,
    LabelList,
    Legend,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis,
} from 'recharts';

export type BarHorizontalRow = {
    name: string;
    noCumple: number;
    cumple: number;
};

export type BarHorizontalProps = {
    data: BarHorizontalRow[];
    className?: string;
    'aria-label'?: string;
    yAxisWidth?: number;
    /** Si se define, fija la altura del gráfico (px); si no, se calcula según la cantidad de filas. */
    height?: number;
};

const NO_CUMPLE_COLOR = '#e70659';
const CUMPLE_COLOR = '#00D8FF';

const MIN_PCT_FOR_LABEL = 8;

function formatBarLabel(value: unknown): string {
    const n = Number(value ?? 0);
    if (!Number.isFinite(n) || n < MIN_PCT_FOR_LABEL) {
        return '';
    }
    return `${n}%`;
}

export default function BarHorizontal({
    data,
    className = 'max-w-5xl',
    'aria-label': ariaLabel = 'Gráfico de barras horizontales apiladas',
    yAxisWidth = 160,
    height: heightProp,
}: BarHorizontalProps) {
    const chartHeight = useMemo(() => {
        if (heightProp != null && heightProp > 0) {
            return heightProp;
        }
        return Math.max(360, data.length * 44);
    }, [data.length, heightProp]);

    return (
        <div className={className} role="img" aria-label={ariaLabel}>
            <ResponsiveContainer width="100%" height={chartHeight}>
                <BarChart
                    layout="vertical"
                    data={data}
                    margin={{ top: 8, right: 16, left: 8, bottom: 8 }}
                    barCategoryGap="12%"
                >
                    <CartesianGrid strokeDasharray="3 3" className="stroke-zinc-200 dark:stroke-zinc-700" />
                    <XAxis
                        type="number"
                        domain={[0, 100]}
                        tickFormatter={(v) => `${v}%`}
                        className="text-xs"
                    />
                    <YAxis
                        type="category"
                        dataKey="name"
                        width={yAxisWidth}
                        tick={{ fontSize: 16 }}
                        interval={0}
                    />
                    <Tooltip
                        formatter={(value, name) => [`${Number(value ?? 0)}%`, String(name ?? '')]}
                        labelFormatter={(label) => String(label)}
                        contentStyle={{ borderRadius: 8 }}
                    />
                    <Legend />
                    <Bar
                        name="No Cumple"
                        dataKey="noCumple"
                        stackId="compliance"
                        fill={NO_CUMPLE_COLOR}
                    >
                        <LabelList
                            dataKey="noCumple"
                            position="center"
                            formatter={formatBarLabel}
                            fill="#ffffff"
                            style={{ fontSize: 11, fontWeight: 700 }}
                        />
                    </Bar>
                    <Bar
                        name="Cumple"
                        dataKey="cumple"
                        stackId="compliance"
                        fill={CUMPLE_COLOR}
                    >
                        <LabelList
                            dataKey="cumple"
                            position="center"
                            formatter={formatBarLabel}
                            fill="#18181b"
                            style={{ fontSize: 11, fontWeight: 700 }}
                        />
                    </Bar>
                </BarChart>
            </ResponsiveContainer>
        </div>
    );
}
