"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  BarChart,
  Bar,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Cell,
  LabelList,
  ReferenceLine,
} from "recharts";
import type {
  DrillChartRow,
  MarketingDrillMetric,
} from "@/features/marketing/utils/marketing-drill-helpers";
import { getDrillMetricValue } 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,
  formatChartValue,
  formatCompactCount,
  formatCompactCurrency,
  percentOfTotal,
} from "./marketing-chart-config";
import {
  MARKETING_BAR_TRACK_FILL,
  marketingChartBarFill,
  marketingChartColor,
} from "./marketing-chart-colors";
import { MarketingChartTooltip } from "./marketing-chart-tooltip";

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

function metricFormat(metric: MarketingDrillMetric): "currency" | "count" | "percent" {
  if (metric === "leads") return "count";
  if (metric === "roi") return "percent";
  return "currency";
}

function formatMetric(metric: MarketingDrillMetric, value: number): string {
  return formatChartValue(
    value,
    metric === "leads" ? "count" : metric === "roi" ? "percent" : "currency",
  );
}

function compactMetric(metric: MarketingDrillMetric, value: number): string {
  if (metric === "leads") return formatCompactCount(value);
  if (metric === "roi") return formatMarketingPercent(value || null);
  return formatCompactCurrency(value);
}

export const MarketingDrillBarChart = React.memo(function MarketingDrillBarChart({
  title,
  subtitle,
  rows,
  metric,
  isLoading,
  onBarClick,
}: MarketingDrillBarChartProps) {
  const chartData = React.useMemo(
    () =>
      [...rows]
        .map((row) => ({
          ...row,
          metricValue: getDrillMetricValue(row, metric),
        }))
        .sort((a, b) => b.metricValue - a.metricValue),
    [rows, metric],
  );

  const total = chartData.reduce((sum, row) => sum + row.metricValue, 0);
  const average =
    chartData.length > 0 ? total / chartData.length : 0;
  const isEmpty = !isLoading && chartData.every((row) => row.metricValue === 0);
  const chartHeight = Math.min(360, Math.max(260, chartData.length * 44));

  return (
    <MarketingChartCard
      title={title}
      subtitle={subtitle}
      isLoading={isLoading}
      isEmpty={isEmpty}
      emptyMessage="No comparison data"
      emptyDescription="Adjust filters or drill to a level with activity."
      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}: ${formatMetric(metric, row.metricValue)}`}
                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: marketingChartColor(index) }}
                >
                  {row.name}
                </div>
                <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                  {formatMetric(metric, row.metricValue)}
                </div>
                <div className="text-xs font-medium text-gray-500">
                  {percentOfTotal(row.metricValue, total).toFixed(1)}% of total
                </div>
              </button>
            ))}
          </div>
        ) : null
      }
    >
      <div style={{ height: chartHeight }}>
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={chartData}
            layout="vertical"
            margin={{ left: 4, right: 48, top: 8, bottom: 4 }}
            barCategoryGap="18%"
          >
            <CartesianGrid
              strokeDasharray="3 3"
              horizontal={false}
              stroke="#CBD5E1"
            />
            <XAxis
              type="number"
              axisLine={false}
              tickLine={false}
              tick={MARKETING_AXIS_TICK}
              tickFormatter={(value) => compactMetric(metric, Number(value))}
            />
            <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={metricFormat(metric)} />
              }
            />
            {chartData.length > 1 ? (
              <ReferenceLine
                x={average}
                stroke="#94A3B8"
                strokeDasharray="4 4"
                label={{
                  value: "Avg",
                  position: "insideTopRight",
                  fill: "#94A3B8",
                  fontSize: 10,
                  fontWeight: 700,
                }}
              />
            ) : null}
            <Bar
              dataKey="metricValue"
              radius={[0, 8, 8, 0]}
              barSize={28}
              minPointSize={4}
              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={marketingChartBarFill(index, {
                    isTeamLead: entry.isTeamLead,
                  })}
                />
              ))}
              <LabelList
                dataKey="metricValue"
                position="right"
                offset={8}
                formatter={(value: number) => compactMetric(metric, value)}
                className="fill-gray-800 text-[11px] font-extrabold"
              />
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </MarketingChartCard>
  );
});
