"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  ComposedChart,
  Bar,
  Line,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Cell,
  LabelList,
  Legend,
} from "recharts";
import type { MarketingAeMetrics } from "@/api/rtk/marketing-api";
import type { MarketingDrillMetric } from "@/features/marketing/utils/marketing-drill-helpers";
import { formatMarketingPercent } from "../marketing-kpi-card";
import { MarketingChartCard } from "./marketing-chart-card";
import {
  MARKETING_AXIS_TICK,
  formatChartValue,
  formatCompactCount,
  formatCompactCurrency,
} from "./marketing-chart-config";
import {
  MARKETING_BAR_TRACK_FILL,
  marketingChartBarFill,
} from "./marketing-chart-colors";
import { MarketingChartTooltip } from "./marketing-chart-tooltip";

type MarketingPersonChannelChartProps = {
  title: string;
  subtitle?: string;
  channels: MarketingAeMetrics[];
  metric: MarketingDrillMetric;
  isLoading?: boolean;
};

function channelMetricValue(
  channel: MarketingAeMetrics,
  metric: MarketingDrillMetric,
): number {
  switch (metric) {
    case "spending":
      return channel.spending;
    case "leads":
      return channel.leads;
    case "roi":
      return channel.roiPct ?? 0;
    case "cpl":
      return channel.cpl ?? 0;
    default:
      return 0;
  }
}

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 MarketingPersonChannelChart = React.memo(
  function MarketingPersonChannelChart({
    title,
    subtitle,
    channels,
    metric,
    isLoading,
  }: MarketingPersonChannelChartProps) {
    const chartData = React.useMemo(
      () =>
        [...channels]
          .map((ch) => ({
            name: ch.channel,
            value: channelMetricValue(ch, metric),
            roiPct: ch.roiPct ?? 0,
            leads: ch.leads,
            spending: ch.spending,
            frontRevenue: ch.frontRevenue,
          }))
          .sort((a, b) => b.value - a.value),
      [channels, metric],
    );

    const isEmpty = !isLoading && chartData.length === 0;
    const showRoiOverlay = metric === "spending" || metric === "leads";
    const maxRoi = Math.max(...chartData.map((r) => r.roiPct), 100);

    const valueFormat =
      metric === "leads" ? "count" : metric === "roi" ? "percent" : "currency";

    return (
      <MarketingChartCard
        title={title}
        subtitle={subtitle}
        isLoading={isLoading}
        isEmpty={isEmpty}
        emptyMessage="No channel performance"
        emptyDescription="Adjust filters or drill down when AE channel data is available."
        chartHeight={300}
        footer={
          chartData.length > 0 ? (
            <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
              {chartData.slice(0, 4).map((row, index) => (
                <div
                  key={row.name}
                  className="rounded-xl border border-gray-100 bg-gray-50/80 px-3 py-2"
                >
                  <div
                    className="truncate text-[10px] font-bold uppercase tracking-wide"
                    style={{ color: marketingChartBarFill(index) }}
                  >
                    {row.name}
                  </div>
                  <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                    {formatChartValue(row.value, valueFormat)}
                  </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>ROI {formatMarketingPercent(row.roiPct || null)}</span>
                  </div>
                </div>
              ))}
            </div>
          ) : null
        }
      >
        <div className="h-[300px]">
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart
              data={chartData}
              margin={{ top: 20, right: showRoiOverlay ? 12 : 8, left: 0, bottom: 4 }}
              barCategoryGap="20%"
            >
              <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="main"
                axisLine={false}
                tickLine={false}
                tick={MARKETING_AXIS_TICK}
                tickFormatter={(value) => compactMetric(metric, Number(value))}
                width={52}
              />
              {showRoiOverlay ? (
                <YAxis
                  yAxisId="roi"
                  orientation="right"
                  axisLine={false}
                  tickLine={false}
                  tick={{ ...MARKETING_AXIS_TICK, fill: "#D97706" }}
                  unit="%"
                  domain={[0, maxRoi * 1.15]}
                  width={44}
                />
              ) : null}
              <Tooltip
                cursor={{ fill: "rgba(108, 99, 255, 0.08)" }}
                content={<MarketingChartTooltip valueFormat={valueFormat} />}
              />
              {showRoiOverlay ? (
                <Legend
                  wrapperStyle={{ fontSize: 11, fontWeight: 700, paddingTop: 8 }}
                  iconType="circle"
                  iconSize={8}
                />
              ) : null}
              <Bar
                yAxisId="main"
                dataKey="value"
                name={
                  metric === "spending"
                    ? "Spending"
                    : metric === "leads"
                      ? "Leads"
                      : metric === "roi"
                        ? "ROI %"
                        : "CPL"
                }
                radius={[8, 8, 0, 0]}
                maxBarSize={48}
                minPointSize={6}
                background={{ fill: MARKETING_BAR_TRACK_FILL, radius: [8, 8, 0, 0] }}
                activeBar={{
                  stroke: "#1E1B4B",
                  strokeWidth: 1.5,
                  radius: [8, 8, 0, 0],
                }}
              >
                {chartData.map((entry, index) => (
                  <Cell key={entry.name} fill={marketingChartBarFill(index)} />
                ))}
                <LabelList
                  dataKey="value"
                  position="top"
                  offset={4}
                  formatter={(value: number) => compactMetric(metric, value)}
                  className="fill-gray-800 text-[10px] font-extrabold"
                />
              </Bar>
              {showRoiOverlay ? (
                <Line
                  yAxisId="roi"
                  type="monotone"
                  dataKey="roiPct"
                  name="ROI %"
                  stroke="#D97706"
                  strokeWidth={2.5}
                  dot={{
                    r: 5,
                    fill: "#D97706",
                    stroke: "#fff",
                    strokeWidth: 2,
                  }}
                  activeDot={{ r: 7 }}
                />
              ) : null}
            </ComposedChart>
          </ResponsiveContainer>
        </div>
      </MarketingChartCard>
    );
  },
);
