import { useTranslation } from 'react-i18next';
import { ts } from '../../i18n/server';
import type { EnumFeatureStats } from '../../types';
import { roundedPercentages } from '../../lib/format';

interface StackedEnumChartProps {
  components: { label: string; stats: EnumFeatureStats }[];
  valueOrder: string[];
  valueColors: string[];
  compact?: boolean;
}

/** Strip common suffixes to produce short row labels */
function shortenLabel(name: string): string {
  return name.replace(/ risk$/, '');
}

function shortenAxisLabel(name: string): string {
  const label = shortenLabel(name);
  if (label.length <= 3) return label;
  const parts = label.split(/[\s/&-]+/).filter(Boolean);
  if (parts.length > 1) {
    return parts
      .map((part) => Array.from(part)[0])
      .join('')
      .slice(0, 3);
  }
  return Array.from(label).slice(0, 3).join('');
}

export default function StackedEnumChart({
  components,
  valueOrder,
  valueColors,
  compact = false,
}: StackedEnumChartProps) {
  const { t } = useTranslation();
  const visibleRows = components.filter(({ stats }) => {
    const total = Object.values(stats.counts).reduce((a, b) => a + b, 0);
    if (total === 0) return false;
    const lowCount = stats.counts[valueOrder[0]] ?? 0;
    return total - lowCount > 0;
  });

  if (visibleRows.length === 0) {
    return (
      <div className="text-xs text-warm-400 dark:text-warm-500 italic mt-1">
        {t('common.allLow')}
      </div>
    );
  }

  if (compact) {
    return (
      <div className="divide-y divide-warm-100 dark:divide-navy-800">
        {visibleRows.map(({ label, stats }) => {
          const counts = valueOrder.map((value) => stats.counts[value] ?? 0);
          const total = counts.reduce((a, b) => a + b, 0);
          const roundedPcts = roundedPercentages(counts, total, 0);
          const title = valueOrder
            .map((value, i) => `${ts(value)}: ${counts[i]} (${roundedPcts[i]}%)`)
            .join('\n');

          return (
            <div
              key={label}
              className="grid min-h-8 grid-cols-[minmax(0,1fr)_6.5rem] items-center gap-3 py-1.5"
            >
              <span className="truncate text-xs font-medium text-warm-800 dark:text-warm-200">
                {shortenLabel(ts(label))}
              </span>
              <div
                className="flex h-5 overflow-hidden rounded-sm bg-warm-200 dark:bg-warm-700"
                title={title}
              >
                {valueOrder.map((value, i) => {
                  const count = counts[i];
                  const pct = (count / total) * 100;
                  if (pct < 0.5) return null;
                  return (
                    <div
                      key={value}
                      className="h-full"
                      style={{
                        width: `${pct}%`,
                        backgroundColor: valueColors[i],
                      }}
                    />
                  );
                })}
              </div>
            </div>
          );
        })}
        <div className="ml-auto grid w-[6.5rem] grid-flow-col auto-cols-fr gap-1 pt-1">
          {valueOrder.map((value) => (
            <span
              key={value}
              className="truncate text-center text-[8px] font-medium leading-none text-warm-500 dark:text-warm-400"
              title={ts(value)}
            >
              {shortenAxisLabel(ts(value))}
            </span>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-1.5">
      {visibleRows.map(({ label, stats }) => {
        const counts = valueOrder.map((value) => stats.counts[value] ?? 0);
        const total = counts.reduce((a, b) => a + b, 0);
        const roundedPcts = roundedPercentages(counts, total, 0);

        return (
          <div key={label} className="flex items-center gap-2 text-xs">
            <span className="w-24 truncate text-warm-500 dark:text-warm-400 text-right shrink-0">
              {shortenLabel(ts(label))}
            </span>
            <div className="flex-1 flex h-3.5 rounded overflow-hidden bg-warm-200 dark:bg-warm-700">
              {valueOrder.map((value, i) => {
                const count = counts[i];
                const pct = (count / total) * 100;
                if (pct < 0.5) return null;
                return (
                  <div
                    key={value}
                    className="h-full"
                    style={{
                      width: `${pct}%`,
                      backgroundColor: valueColors[i],
                    }}
                    title={`${ts(value)}: ${count} (${roundedPcts[i]}%)`}
                  />
                );
              })}
            </div>
          </div>
        );
      })}

      {/* Legend */}
      <div className="flex gap-x-3 gap-y-0.5 justify-center">
        {valueOrder.map((value, i) => (
          <div key={value} className="flex items-center gap-1">
            <span
              className="w-2 h-2 rounded-sm shrink-0"
              style={{ backgroundColor: valueColors[i] }}
            />
            <span className="text-[10px] text-warm-600 dark:text-warm-400">{ts(value)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
