'use client';

import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { TodayChartFrame } from '@/components/ui/today/TodayChartFrame';
import type { TodayChartBucket } from '@/types/today';
import {
  chartRankColor,
  TODAY_CHART_AXIS_COLOR,
  TODAY_CHART_GRID_COLOR,
  TODAY_CHART_TOOLTIP_STYLE,
} from '@/components/today/chart-theme';

interface TodayHorizontalBarChartProps {
  data: TodayChartBucket[];
}

export function TodayHorizontalBarChart({ data }: TodayHorizontalBarChartProps) {
  const chartData = data.map((item) => ({
    ...item,
    shortLabel: truncateLabel(item.label, 18),
  }));

  return (
    <TodayChartFrame>
      <ResponsiveContainer width="100%" height="100%">
        <BarChart
          data={chartData}
          layout="vertical"
          margin={{ top: 4, right: 12, left: 4, bottom: 4 }}
        >
          <CartesianGrid stroke={TODAY_CHART_GRID_COLOR} horizontal={false} />
          <XAxis
            type="number"
            allowDecimals={false}
            tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: 11 }}
            axisLine={{ stroke: TODAY_CHART_GRID_COLOR }}
            tickLine={false}
          />
          <YAxis
            type="category"
            dataKey="shortLabel"
            width={96}
            tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: 11 }}
            axisLine={false}
            tickLine={false}
          />
          <Tooltip
            cursor={{ fill: 'rgba(0, 188, 255, 0.08)' }}
            contentStyle={TODAY_CHART_TOOLTIP_STYLE}
            labelFormatter={(_, payload) => {
              const row = payload?.[0]?.payload as TodayChartBucket | undefined;
              return row?.label ?? '';
            }}
          />
          <Bar dataKey="count" radius={[0, 4, 4, 0]} maxBarSize={28}>
            {chartData.map((entry, index) => (
              <Cell
                key={entry.code}
                fill={chartRankColor(index)}
              />
            ))}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </TodayChartFrame>
  );
}

function truncateLabel(label: string, max = 18): string {
  if (label.length <= max) return label;
  return `${label.slice(0, max - 1)}…`;
}
