'use client';

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

interface TodayPartnerCasesStackedBarChartProps {
  data: TodayPartnerCasesBucket[];
  completedLabel: string;
  pendingLabel: string;
  onPartnerClick?: (partner: TodayPartnerCasesBucket) => void;
}

export function TodayPartnerCasesStackedBarChart({
  data,
  completedLabel,
  pendingLabel,
  onPartnerClick,
}: TodayPartnerCasesStackedBarChartProps) {
  const chartData = data.map((item) => ({
    ...item,
    shortLabel: truncateLabel(item.label),
  }));

  const handlePartnerClick = (payload: { code?: string } | undefined) => {
    if (!onPartnerClick || !payload?.code) return;
    const partner = chartData.find((row) => row.code === payload.code);
    if (partner) onPartnerClick(partner);
  };

  return (
    <TodayChartFrame>
      <div className="flex h-full min-h-0 flex-col">
        <div className="min-h-0 flex-1">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={chartData} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
              <CartesianGrid stroke={TODAY_CHART_GRID_COLOR} vertical={false} />
              <XAxis
                dataKey="shortLabel"
                tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: 11 }}
                axisLine={{ stroke: TODAY_CHART_GRID_COLOR }}
                tickLine={false}
                interval={chartData.length <= 8 ? 0 : 'preserveStartEnd'}
                minTickGap={chartData.length > 8 ? 28 : undefined}
              />
              <YAxis
                allowDecimals={false}
                tick={{ fill: TODAY_CHART_AXIS_COLOR, fontSize: 11 }}
                axisLine={false}
                tickLine={false}
                width={32}
              />
              <Tooltip
                cursor={{ fill: 'rgba(0, 188, 255, 0.08)' }}
                contentStyle={TODAY_CHART_TOOLTIP_STYLE}
                labelFormatter={(_, payload) => {
                  const row = payload?.[0]?.payload as TodayPartnerCasesBucket | undefined;
                  return row?.label ?? '';
                }}
              />
              <Bar
                dataKey="completed"
                name={completedLabel}
                stackId="cases"
                fill={TODAY_CHART_COMPLETED_COLOR}
                radius={[0, 0, 0, 0]}
                maxBarSize={48}
                className={onPartnerClick ? 'cursor-pointer' : undefined}
                onClick={(payload) => handlePartnerClick(payload as { code?: string })}
              />
              <Bar
                dataKey="pending"
                name={pendingLabel}
                stackId="cases"
                fill={TODAY_CHART_RECEIVED_COLOR}
                radius={[4, 4, 0, 0]}
                maxBarSize={48}
                className={onPartnerClick ? 'cursor-pointer' : undefined}
                onClick={(payload) => handlePartnerClick(payload as { code?: string })}
              />
            </BarChart>
          </ResponsiveContainer>
        </div>

        <div className="mt-0.5 flex shrink-0 flex-wrap items-center justify-center gap-x-4 gap-y-0.5 pb-0 text-[11px] text-text-muted">
          <span className="inline-flex items-center gap-1.5">
            <span
              className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm"
              style={{ backgroundColor: TODAY_CHART_COMPLETED_COLOR }}
              aria-hidden
            />
            {completedLabel}
          </span>
          <span className="inline-flex items-center gap-1.5">
            <span
              className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm"
              style={{ backgroundColor: TODAY_CHART_RECEIVED_COLOR }}
              aria-hidden
            />
            {pendingLabel}
          </span>
        </div>
      </div>
    </TodayChartFrame>
  );
}

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