import React, { useCallback, useMemo, useState } from 'react';
import {
  CompletionByTypeData,
  CompletionByTypeRate,
  REPAIR_COMPLETION_BAR_COLORS,
  getRepairCompletionRate,
  isNullOrUnknownLabel,
} from '../utils/chartLabelUtils';

type TooltipState = {
  x: number;
  y: number;
  rate: CompletionByTypeRate;
  color: string;
  percentage: number;
};

type RepairStatusCompletionBarChartProps = {
  data: CompletionByTypeData | null;
};

const RepairStatusCompletionBarChart: React.FC<RepairStatusCompletionBarChartProps> = ({ data }) => {
  const [tooltip, setTooltip] = useState<TooltipState | null>(null);

  const rates = useMemo(
    () => (data?.rates || []).filter(item => !isNullOrUnknownLabel(item.type)),
    [data]
  );

  const hideTooltip = useCallback(() => setTooltip(null), []);

  if (!rates.length) {
    return (
      <div className="h-44 flex items-center justify-center text-gray-400 text-sm">
        No completion data available
      </div>
    );
  }

  const chartHeight = 160;
  const barWidth = 44;
  const barGap = 18;
  const paddingLeft = 36;
  const paddingRight = 16;
  const width = paddingLeft + rates.length * (barWidth + barGap) + paddingRight;
  const gridLines = [0, 25, 50, 75, 100];

  return (
    <div className="relative w-full overflow-x-auto" onMouseLeave={hideTooltip}>
      {tooltip && (
        <div
          className="fixed z-[9999] pointer-events-none rounded-lg bg-gray-900 text-white px-3 py-2 text-xs shadow-lg max-w-[220px]"
          style={{ left: tooltip.x, top: tooltip.y - 8, transform: 'translate(-50%, -100%)' }}
        >
          <div className="flex items-center gap-2 mb-1">
            <span className="w-2.5 h-2.5 rounded-sm shrink-0" style={{ backgroundColor: tooltip.color }} />
            <span className="font-semibold truncate">{tooltip.rate.type}</span>
          </div>
          <div className="text-emerald-300 font-semibold">{tooltip.percentage.toFixed(1)}% Completed</div>
          <div className="text-gray-300 mt-1">
            {(tooltip.rate.completedCombined ?? (tooltip.rate.completed || 0) + (tooltip.rate.closed || 0))} completed ·{' '}
            {tooltip.rate.inProgress || 0} prog · {tooltip.rate.rejected || 0} rej
          </div>
          <div className="text-gray-400">{tooltip.rate.total || 0} total</div>
        </div>
      )}

      <svg width={width} height={chartHeight + 56} className="min-w-full">
        {gridLines.map(level => {
          const y = chartHeight - (level / 100) * chartHeight + 8;
          return (
            <g key={level}>
              <line x1={paddingLeft} y1={y} x2={width - paddingRight} y2={y} stroke="#E5E7EB" strokeWidth="1" />
              <text x={paddingLeft - 8} y={y + 4} textAnchor="end" className="fill-gray-400 text-[10px]">
                {level}%
              </text>
            </g>
          );
        })}

        {rates.map((rate, index) => {
          const percentage = getRepairCompletionRate(rate);
          const barHeight = Math.max(2, (percentage / 100) * chartHeight);
          const x = paddingLeft + index * (barWidth + barGap);
          const y = chartHeight - barHeight + 8;
          const color = REPAIR_COMPLETION_BAR_COLORS[index % REPAIR_COMPLETION_BAR_COLORS.length];
          const label = rate.type.length > 12 ? `${rate.type.slice(0, 10)}…` : rate.type;

          return (
            <g key={rate.type}>
              <rect
                x={x}
                y={y}
                width={barWidth}
                height={barHeight}
                rx={4}
                fill={color}
                className="hover:opacity-85 transition-opacity cursor-default"
                onMouseEnter={(e) =>
                  setTooltip({
                    x: e.clientX,
                    y: e.clientY,
                    rate,
                    color,
                    percentage,
                  })
                }
                onMouseMove={(e) =>
                  setTooltip({
                    x: e.clientX,
                    y: e.clientY,
                    rate,
                    color,
                    percentage,
                  })
                }
                onMouseLeave={hideTooltip}
              />
              <text
                x={x + barWidth / 2}
                y={chartHeight + 24}
                textAnchor="middle"
                className="fill-gray-500 text-[10px]"
              >
                {label}
              </text>
            </g>
          );
        })}
      </svg>

      <div className="flex flex-wrap gap-3 mt-1 px-1">
        {rates.slice(0, 6).map((rate, index) => (
          <div key={rate.type} className="flex items-center gap-1.5 text-[10px] text-gray-500">
            <span
              className="w-2.5 h-2.5 rounded-sm shrink-0"
              style={{ backgroundColor: REPAIR_COMPLETION_BAR_COLORS[index % REPAIR_COMPLETION_BAR_COLORS.length] }}
            />
            <span className="truncate max-w-[100px]">{rate.type}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default RepairStatusCompletionBarChart;
