"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  ComposedChart,
  Bar,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  LabelList,
} 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,
  formatCompactCurrency,
  formatChartValue,
} from "./marketing-chart-config";
import {
  MARKETING_BAR_TRACK_FILL,
  MARKETING_REVENUE_BAR_FILL,
  MARKETING_SPEND_BAR_FILL,
} from "./marketing-chart-colors";
import { MarketingDualAxisTooltip } from "./marketing-chart-tooltip";

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

export const MarketingSpendRevenueChart = React.memo(
  function MarketingSpendRevenueChart({
    title,
    subtitle,
    rows,
    isLoading,
    onBarClick,
  }: MarketingSpendRevenueChartProps) {
    const chartData = React.useMemo(
      () =>
        rows.map((row) => ({
          ...row,
          roiValue: row.roiPct ?? 0,
        })),
      [rows],
    );

    const isEmpty =
      !isLoading && rows.every((r) => r.spending === 0 && r.frontRevenue === 0);

    return (
      <MarketingChartCard
        title={title}
        subtitle={subtitle}
        isLoading={isLoading}
        isEmpty={isEmpty}
        emptyMessage="No spend vs revenue"
        chartHeight={300}
        headerRight={
          chartData.length > 0 ? (
            <span className="rounded-full bg-emerald-50 px-2.5 py-1 text-[10px] font-bold text-emerald-700">
              Dual-axis view
            </span>
          ) : null
        }
        footer={
          chartData.length > 0 ? (
            <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
              {chartData.map((row) => (
                <button
                  key={row.id}
                  type="button"
                  aria-label={`View ${row.name}: spending ${formatChartValue(row.spending, "currency")}, revenue ${formatChartValue(row.frontRevenue, "currency")}`}
                  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 text-text">
                    {row.name}
                  </div>
                  <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] font-semibold">
                    <span className="text-red-600">
                      Spend {formatCompactCurrency(row.spending)}
                    </span>
                    <span className="text-emerald-600">
                      Revenue {formatCompactCurrency(row.frontRevenue)}
                    </span>
                  </div>
                  <div className="mt-0.5 text-xs font-medium text-gray-500">
                    ROI{" "}
                    <span className="font-extrabold text-indigo-600">
                      {formatMarketingPercent(row.roiValue || null)}
                    </span>
                  </div>
                </button>
              ))}
            </div>
          ) : null
        }
      >
        <div className="h-[300px]">
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart
              data={chartData}
              margin={{ top: 20, right: 12, left: 0, bottom: 4 }}
              barCategoryGap="24%"
              barGap={6}
            >
              <CartesianGrid
                strokeDasharray="3 3"
                vertical={false}
                stroke="#CBD5E1"
              />
              <XAxis
                dataKey="name"
                axisLine={false}
                tickLine={false}
                tick={MARKETING_AXIS_TICK}
                interval={0}
                angle={chartData.length > 4 ? -18 : 0}
                textAnchor={chartData.length > 4 ? "end" : "middle"}
                height={chartData.length > 4 ? 56 : 32}
              />
              <YAxis
                yAxisId="spend"
                axisLine={false}
                tickLine={false}
                tick={{ ...MARKETING_AXIS_TICK, fill: MARKETING_SPEND_BAR_FILL }}
                tickFormatter={formatCompactCurrency}
                width={52}
              />
              <YAxis
                yAxisId="revenue"
                orientation="right"
                axisLine={false}
                tickLine={false}
                tick={{ ...MARKETING_AXIS_TICK, fill: MARKETING_REVENUE_BAR_FILL }}
                tickFormatter={formatCompactCurrency}
                width={52}
              />
              <Tooltip content={<MarketingDualAxisTooltip />} />
              <Legend
                wrapperStyle={{ fontSize: 11, fontWeight: 700, paddingTop: 8 }}
                iconType="circle"
                iconSize={8}
              />
              <Bar
                yAxisId="spend"
                dataKey="spending"
                name="Spending"
                fill={MARKETING_SPEND_BAR_FILL}
                radius={[6, 6, 0, 0]}
                maxBarSize={40}
                minPointSize={4}
                background={{ fill: MARKETING_BAR_TRACK_FILL, radius: [6, 6, 0, 0] }}
                activeBar={{
                  stroke: "#991B1B",
                  strokeWidth: 1.5,
                  radius: [6, 6, 0, 0],
                }}
                className={onBarClick ? "cursor-pointer" : undefined}
                onClick={(data) => {
                  if (onBarClick && data?.payload) {
                    onBarClick(data.payload as DrillChartRow);
                  }
                }}
              >
                <LabelList
                  dataKey="spending"
                  position="top"
                  offset={4}
                  formatter={(value: number) => formatCompactCurrency(value)}
                  className="fill-red-800 text-[10px] font-extrabold"
                />
              </Bar>
              <Bar
                yAxisId="revenue"
                dataKey="frontRevenue"
                name="Front Revenue"
                fill={MARKETING_REVENUE_BAR_FILL}
                radius={[6, 6, 0, 0]}
                maxBarSize={40}
                minPointSize={4}
                background={{ fill: MARKETING_BAR_TRACK_FILL, radius: [6, 6, 0, 0] }}
                activeBar={{
                  stroke: "#166534",
                  strokeWidth: 1.5,
                  radius: [6, 6, 0, 0],
                }}
                className={onBarClick ? "cursor-pointer" : undefined}
                onClick={(data) => {
                  if (onBarClick && data?.payload) {
                    onBarClick(data.payload as DrillChartRow);
                  }
                }}
              >
                <LabelList
                  dataKey="frontRevenue"
                  position="top"
                  offset={4}
                  formatter={(value: number) => formatCompactCurrency(value)}
                  className="fill-emerald-800 text-[10px] font-extrabold"
                />
              </Bar>
            </ComposedChart>
          </ResponsiveContainer>
        </div>
      </MarketingChartCard>
    );
  },
);
