"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  ComposedChart,
  Area,
  Line,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
} from "recharts";
import type { MarketingTrendPoint } from "@/api/rtk/marketing-api";
import { formatMarketingPercent } from "../marketing-kpi-card";
import { MarketingChartCard } from "./marketing-chart-card";
import {
  MARKETING_AXIS_TICK,
  formatCompactCount,
  formatCompactCurrency,
} from "./marketing-chart-config";
import {
  MARKETING_REVENUE_BAR_FILL,
  MARKETING_SPEND_BAR_FILL,
} from "./marketing-chart-colors";
import { MarketingDualAxisTooltip } from "./marketing-chart-tooltip";

const REVENUE_AREA_GRADIENT_ID = "marketing-trend-revenue-area";

type MarketingTrendAreaChartProps = {
  title: string;
  subtitle?: string;
  data: MarketingTrendPoint[];
  isLoading?: boolean;
  isFallback?: boolean;
};

const trendDot = (color: string) => ({
  r: 5,
  fill: color,
  stroke: "#fff",
  strokeWidth: 2,
});

/** Area + line trend: revenue fill, spending dashed overlay, leads on right axis. */
export const MarketingTrendAreaChart = React.memo(function MarketingTrendAreaChart({
  title,
  subtitle,
  data,
  isLoading,
  isFallback,
}: MarketingTrendAreaChartProps) {
  const chartData = React.useMemo(
    () =>
      data.map((point) => ({
        ...point,
        roiPct:
          point.spending > 0
            ? (point.frontRevenue / point.spending) * 100
            : 0,
      })),
    [data],
  );

  const isEmpty = !isLoading && chartData.length === 0;

  const totals = React.useMemo(
    () =>
      chartData.reduce(
        (acc, point) => ({
          spending: acc.spending + point.spending,
          frontRevenue: acc.frontRevenue + point.frontRevenue,
          leads: acc.leads + point.leads,
        }),
        { spending: 0, frontRevenue: 0, leads: 0 },
      ),
    [chartData],
  );

  const totalRoi =
    totals.spending > 0 ? (totals.frontRevenue / totals.spending) * 100 : null;

  return (
    <MarketingChartCard
      title={title}
      subtitle={subtitle}
      isLoading={isLoading}
      isEmpty={isEmpty}
      emptyMessage="No trend data"
      emptyDescription="Set a date range to see monthly spending and leads."
      chartHeight={300}
      headerRight={
        isFallback ? (
          <span className="rounded-full bg-amber-50 px-2.5 py-1 text-[10px] font-bold text-amber-700">
            Period summary
          </span>
        ) : (
          <span className="rounded-full bg-emerald-50 px-2.5 py-1 text-[10px] font-bold text-emerald-700">
            Area trend
          </span>
        )
      }
      footer={
        chartData.length > 0 ? (
          <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
            <div className="rounded-xl border border-gray-100 bg-gray-50/80 px-3 py-2">
              <div className="text-[10px] font-bold uppercase tracking-wide text-red-600">
                Total spend
              </div>
              <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                {formatCompactCurrency(totals.spending)}
              </div>
            </div>
            <div className="rounded-xl border border-gray-100 bg-gray-50/80 px-3 py-2">
              <div className="text-[10px] font-bold uppercase tracking-wide text-emerald-600">
                Total revenue
              </div>
              <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                {formatCompactCurrency(totals.frontRevenue)}
              </div>
            </div>
            <div className="rounded-xl border border-gray-100 bg-gray-50/80 px-3 py-2">
              <div className="text-[10px] font-bold uppercase tracking-wide text-indigo-600">
                Total leads
              </div>
              <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                {formatCompactCount(totals.leads)}
              </div>
            </div>
            <div className="rounded-xl border border-gray-100 bg-gray-50/80 px-3 py-2">
              <div className="text-[10px] font-bold uppercase tracking-wide text-amber-600">
                ROI
              </div>
              <div className="mt-0.5 text-sm font-extrabold tabular-nums text-text">
                {formatMarketingPercent(totalRoi)}
              </div>
            </div>
          </div>
        ) : null
      }
    >
      <div className="h-[300px]">
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart
            data={chartData}
            margin={{ top: 16, right: 12, left: 0, bottom: 4 }}
          >
            <defs>
              <linearGradient
                id={REVENUE_AREA_GRADIENT_ID}
                x1="0"
                y1="0"
                x2="0"
                y2="1"
              >
                <stop
                  offset="5%"
                  stopColor={MARKETING_REVENUE_BAR_FILL}
                  stopOpacity={0.35}
                />
                <stop
                  offset="95%"
                  stopColor={MARKETING_REVENUE_BAR_FILL}
                  stopOpacity={0.04}
                />
              </linearGradient>
            </defs>
            <CartesianGrid
              strokeDasharray="3 3"
              vertical={false}
              stroke="#CBD5E1"
            />
            <XAxis
              dataKey="label"
              axisLine={false}
              tickLine={false}
              tick={MARKETING_AXIS_TICK}
            />
            <YAxis
              yAxisId="currency"
              axisLine={false}
              tickLine={false}
              tick={{ ...MARKETING_AXIS_TICK, fill: MARKETING_REVENUE_BAR_FILL }}
              tickFormatter={formatCompactCurrency}
              width={52}
            />
            <YAxis
              yAxisId="count"
              orientation="right"
              axisLine={false}
              tickLine={false}
              tick={{ ...MARKETING_AXIS_TICK, fill: "#4F46E5" }}
              tickFormatter={formatCompactCount}
              width={44}
            />
            <Tooltip
              cursor={{ stroke: "#94A3B8", strokeWidth: 1, strokeDasharray: "4 4" }}
              content={<MarketingDualAxisTooltip />}
            />
            <Legend
              wrapperStyle={{ fontSize: 11, fontWeight: 700, paddingTop: 8 }}
              iconType="circle"
              iconSize={8}
            />
            <Area
              yAxisId="currency"
              type="monotone"
              dataKey="frontRevenue"
              name="Front Revenue"
              stroke={MARKETING_REVENUE_BAR_FILL}
              strokeWidth={2.5}
              fill={`url(#${REVENUE_AREA_GRADIENT_ID})`}
              dot={trendDot(MARKETING_REVENUE_BAR_FILL)}
              activeDot={{ r: 7 }}
            />
            <Line
              yAxisId="currency"
              type="monotone"
              dataKey="spending"
              name="Spending"
              stroke={MARKETING_SPEND_BAR_FILL}
              strokeWidth={2}
              strokeDasharray="6 4"
              dot={trendDot(MARKETING_SPEND_BAR_FILL)}
              activeDot={{ r: 7 }}
            />
            <Line
              yAxisId="count"
              type="monotone"
              dataKey="leads"
              name="Leads"
              stroke="#4F46E5"
              strokeWidth={2.5}
              dot={trendDot("#4F46E5")}
              activeDot={{ r: 7 }}
            />
          </ComposedChart>
        </ResponsiveContainer>
      </div>
    </MarketingChartCard>
  );
});
