import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ts } from '../../i18n/server';
import { formatValue, roundedPercentages } from '../../lib/format';

interface Segment {
  name: string;
  value: number;
}

interface StackedBarChartProps {
  segments: Segment[];
  total: number;
  colorMap: Record<string, string>;
  compact?: boolean;
}

/** Strip common suffixes/prefixes to produce short legend labels */
function shortenLabel(name: string): string {
  return name
    .replace(' (avg/yr)', '')
    .replace(/^% /, '')
    .replace('and sexual offences', '')
    .replace('and arson', '')
    .replace('from the person', '')
    .replace('Possession of weapons', 'Weapons')
    .replace('Anti-social behaviour', 'Anti-social')
    .replace('Criminal damage', 'Damage')
    .trim();
}

function shortenAxisLabel(name: string, total: number): 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, total <= 5 ? 3 : 2)
    .join('');
}

export default function StackedBarChart({
  segments,
  total,
  colorMap,
  compact = false,
}: StackedBarChartProps) {
  const { t } = useTranslation();
  const sortedSegments = useMemo(() => [...segments].sort((a, b) => b.value - a.value), [segments]);
  const roundedPcts = useMemo(
    () =>
      roundedPercentages(
        sortedSegments.map((s) => s.value),
        total,
        1
      ),
    [sortedSegments, total]
  );

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

  const colorFor = (segmentName: string): string => {
    const color = colorMap[segmentName];
    if (!color) {
      throw new Error(`Missing stacked bar color for '${segmentName}'`);
    }
    return color;
  };

  if (compact) {
    const maxValue = Math.max(...sortedSegments.map((segment) => segment.value), 1);
    const showAxisLabels = sortedSegments.length <= 8;
    const title = sortedSegments
      .map((segment, i) => {
        const label = shortenLabel(ts(segment.name));
        return `${label}: ${formatValue(segment.value)} (${roundedPcts[i].toFixed(1)}%)`;
      })
      .join('\n');

    return (
      <div className={showAxisLabels ? 'h-10' : 'h-7'} title={title}>
        <div className={`${showAxisLabels ? 'h-7' : 'h-full'} flex items-end gap-[2px]`}>
          {sortedSegments.map((segment) => {
            const height = (segment.value / maxValue) * 100;
            return (
              <div
                key={segment.name}
                className="min-w-[3px] flex-1 rounded-t-[2px]"
                style={{
                  height: `${Math.max(height, 12)}%`,
                  backgroundColor: colorFor(segment.name),
                }}
              />
            );
          })}
        </div>
        {showAxisLabels && (
          <div className="mt-0.5 flex gap-[2px]">
            {sortedSegments.map((segment) => {
              const label = shortenLabel(ts(segment.name));
              return (
                <span
                  key={segment.name}
                  className="min-w-[3px] flex-1 truncate text-center text-[8px] font-medium leading-none text-warm-500 dark:text-warm-400"
                  title={label}
                >
                  {shortenAxisLabel(label, sortedSegments.length)}
                </span>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="space-y-1.5">
      {/* Stacked bar */}
      <div className="flex h-4 rounded overflow-hidden bg-warm-200 dark:bg-warm-700">
        {sortedSegments.map((segment, i) => {
          const pct = (segment.value / total) * 100;
          if (pct < 0.5) return null;
          const label = shortenLabel(ts(segment.name));
          return (
            <div
              key={segment.name}
              className="h-full"
              style={{
                width: `${pct}%`,
                backgroundColor: colorFor(segment.name),
              }}
              title={`${label}: ${formatValue(segment.value)} (${roundedPcts[i].toFixed(1)}%)`}
            />
          );
        })}
      </div>

      {/* Legend */}
      <div className="flex flex-wrap gap-x-3 gap-y-0.5">
        {sortedSegments.map((segment) => {
          const label = shortenLabel(ts(segment.name));
          return (
            <div key={segment.name} className="flex items-center gap-1">
              <span
                className="w-2 h-2 rounded-sm shrink-0"
                style={{
                  backgroundColor: colorFor(segment.name),
                }}
              />
              <span className="text-[10px] text-warm-600 dark:text-warm-400">{label}</span>
              <span className="text-[10px] text-warm-400 dark:text-warm-500">
                {formatValue(segment.value)}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}
