"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  ComposedChart,
  Bar,
  Line,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
} 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_GRID_STROKE,
  formatCompactCount,
} from "./marketing-chart-config";
import { MarketingChartGradientDefs } from "./marketing-chart-gradients";
import { MarketingDualAxisTooltip } from "./marketing-chart-tooltip";

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

export const MarketingLeadsAccountsChart = React.memo(
  function MarketingLeadsAccountsChart({
    title,
    subtitle,
    rows,
    isLoading,
    onBarClick,
  }: MarketingLeadsAccountsChartProps) {
    const chartData = React.useMemo(
      () =>
        rows.map((row) => ({
          ...row,
          conversionPct:
            row.leads > 0 ? (row.accounts / row.leads) * 100 : 0,
        })),
      [rows],
    );

    const isEmpty =
      !isLoading && rows.every((r) => r.leads === 0 && r.accounts === 0);

    const maxConversion = Math.max(
      ...chartData.map((r) => r.conversionPct),
      100,
    );

    return (
      <MarketingChartCard
        title={title}
        subtitle={subtitle}
        isLoading={isLoading}
        isEmpty={isEmpty}
        emptyMessage="No leads vs accounts"
        chartHeight={300}
        headerRight={
          <span className="rounded-full bg-indigo-50 px-2.5 py-1 text-[10px] font-bold text-indigo-700">
            Conversion overlay
          </span>
        }
      >
        <div className="h-[300px]">
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart
              data={chartData}
              margin={{ top: 12, right: 12, left: 0, bottom: 4 }}
            >
              <MarketingChartGradientDefs />
              <CartesianGrid
                strokeDasharray="3 3"
                vertical={false}
                stroke={MARKETING_GRID_STROKE}
              />
              <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="count"
                axisLine={false}
                tickLine={false}
                tick={MARKETING_AXIS_TICK}
                tickFormatter={formatCompactCount}
                width={44}
              />
              <YAxis
                yAxisId="conversion"
                orientation="right"
                axisLine={false}
                tickLine={false}
                tick={{ ...MARKETING_AXIS_TICK, fill: "#F59E0B" }}
                unit="%"
                domain={[0, maxConversion * 1.15]}
                width={44}
              />
              <Tooltip content={<MarketingDualAxisTooltip />} />
              <Legend
                wrapperStyle={{ fontSize: 11, fontWeight: 700, paddingTop: 8 }}
                iconType="circle"
                iconSize={8}
              />
              <Bar
                yAxisId="count"
                dataKey="leads"
                name="Leads"
                fill="url(#marketing-gradient-indigo)"
                radius={[6, 6, 0, 0]}
                maxBarSize={36}
                onClick={(data) => {
                  if (onBarClick && data?.payload) {
                    onBarClick(data.payload as DrillChartRow);
                  }
                }}
              />
              <Bar
                yAxisId="count"
                dataKey="accounts"
                name="Accounts"
                fill="url(#marketing-gradient-success)"
                radius={[6, 6, 0, 0]}
                maxBarSize={36}
                onClick={(data) => {
                  if (onBarClick && data?.payload) {
                    onBarClick(data.payload as DrillChartRow);
                  }
                }}
              />
              <Line
                yAxisId="conversion"
                type="monotone"
                dataKey="conversionPct"
                name="Conversion %"
                stroke="#F59E0B"
                strokeWidth={2.5}
                dot={{ r: 4, fill: "#F59E0B", strokeWidth: 0 }}
                activeDot={{ r: 6 }}
              />
            </ComposedChart>
          </ResponsiveContainer>
        </div>
        {chartData.length > 0 ? (
          <p className="mt-2 text-center text-[10px] font-medium text-gray-500">
            Best converter:{" "}
            <span className="font-bold text-amber-600">
              {
                [...chartData].sort(
                  (a, b) => b.conversionPct - a.conversionPct,
                )[0]?.name
              }{" "}
              (
              {formatMarketingPercent(
                [...chartData].sort(
                  (a, b) => b.conversionPct - a.conversionPct,
                )[0]?.conversionPct || null,
              )}
              )
            </span>
          </p>
        ) : null}
      </MarketingChartCard>
    );
  },
);
