"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Cell,
  LabelList,
  ReferenceLine,
} from "recharts";
import type { DrillChartRow } from "@/features/marketing/utils/marketing-drill-helpers";
import { formatMarketingPercent } from "../marketing-kpi-card";
import { MarketingChartCard } from "./marketing-chart-card";
import {
  MARKETING_AXIS_TICK,
  MARKETING_CATEGORY_TICK,
  formatCompactCurrency,
} from "./marketing-chart-config";
import {
  MARKETING_BAR_TRACK_FILL,
  MARKETING_REVENUE_BAR_FILL,
  marketingChartBarFill,
} from "./marketing-chart-colors";
import { MarketingChartTooltip } from "./marketing-chart-tooltip";

type MarketingRoiBarChartProps = {
  title: string;
  subtitle?: string;
  rows: DrillChartRow[];
  isLoading?: boolean;
  onBarClick?: (row: DrillChartRow) => void;
};

function roiBarFill(roiValue: number, average: number, index: number): string {
  if (roiValue >= average) return MARKETING_REVENUE_BAR_FILL;
  return marketingChartBarFill(index);
}

export const MarketingRoiBarChart = React.memo(function MarketingRoiBarChart({
  title,
  subtitle,
  rows,
  isLoading,
  onBarClick,
}: MarketingRoiBarChartProps) {
  const chartData = React.useMemo(
    () =>
      [...rows]
        .map((row) => ({
          ...row,
          roiValue: row.roiPct ?? 0,
        }))
        .sort((a, b) => b.roiValue - a.roiValue),
    [rows],
  );

  const average =
    chartData.length > 0
      ? chartData.reduce((sum, row) => sum + row.roiValue, 0) / chartData.length
      : 0;
  const isEmpty = !isLoading && chartData.every((r) => r.roiValue === 0);
  const chartHeight = Math.min(320, Math.max(240, chartData.length * 52));

  return (
    <MarketingChartCard
      title={title}
      subtitle={subtitle}
      isLoading={isLoading}
      isEmpty={isEmpty}
      emptyMessage="No ROI data"
      chartHeight={chartHeight}
      footer={
        chartData.length > 0 ? (
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
            {chartData.slice(0, 4).map((row, index) => (
              <button
                key={row.id}
                type="button"
                aria-label={`View ${row.name}: ROI ${formatMarketingPercent(row.roiValue || null)}`}
                onClick={() => onBarClick?.(row)}
                className="min-h-11 rounded-xl border border-gray-100 bg-gray-50/80 px-3 py-2 text-left transition-colors hover:border-[#6C63FF]/30 hover:bg-white"
              >
                <div
                  className="truncate text-xs font-bold uppercase tracking-wide"
                  style={{ color: roiBarFill(row.roiValue, average, index) }}
                >
                  {row.name}
                </div>
                <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                  {formatMarketingPercent(row.roiValue || null)}
                </div>
                <div className="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[10px] font-semibold text-gray-500">
                  <span>Spend {formatCompactCurrency(row.spending)}</span>
                  <span>Rev {formatCompactCurrency(row.frontRevenue)}</span>
                </div>
              </button>
            ))}
          </div>
        ) : null
      }
    >
      <div style={{ height: chartHeight }}>
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={chartData}
            layout="vertical"
            margin={{ left: 4, right: 56, top: 8, bottom: 4 }}
            barCategoryGap="18%"
          >
            <CartesianGrid
              strokeDasharray="3 3"
              horizontal={false}
              stroke="#CBD5E1"
            />
            <XAxis
              type="number"
              unit="%"
              axisLine={false}
              tickLine={false}
              tick={MARKETING_AXIS_TICK}
            />
            <YAxis
              dataKey="name"
              type="category"
              width={128}
              axisLine={false}
              tickLine={false}
              tick={MARKETING_CATEGORY_TICK}
            />
            <Tooltip
              cursor={{ fill: "rgba(108, 99, 255, 0.08)" }}
              content={<MarketingChartTooltip valueFormat="percent" />}
            />
            {chartData.length > 1 ? (
              <ReferenceLine
                x={average}
                stroke="#94A3B8"
                strokeDasharray="4 4"
                label={{
                  value: `Avg ${formatMarketingPercent(average || null)}`,
                  position: "insideTopRight",
                  fill: "#64748B",
                  fontSize: 10,
                  fontWeight: 700,
                }}
              />
            ) : null}
            <Bar
              dataKey="roiValue"
              radius={[0, 8, 8, 0]}
              barSize={28}
              minPointSize={6}
              background={{ fill: MARKETING_BAR_TRACK_FILL, radius: [0, 8, 8, 0] }}
              activeBar={{
                stroke: "#1E1B4B",
                strokeWidth: 1.5,
                radius: [0, 8, 8, 0],
              }}
              className={onBarClick ? "cursor-pointer" : undefined}
              onClick={(data) => {
                if (onBarClick && data?.payload) {
                  onBarClick(data.payload as DrillChartRow);
                }
              }}
            >
              {chartData.map((entry, index) => (
                <Cell
                  key={entry.id}
                  fill={roiBarFill(entry.roiValue, average, index)}
                />
              ))}
              <LabelList
                dataKey="roiValue"
                position="right"
                offset={8}
                formatter={(value: number) =>
                  formatMarketingPercent(value || null)
                }
                className="fill-gray-800 text-[11px] font-extrabold"
              />
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </MarketingChartCard>
  );
});
