"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Tooltip,
  Sector,
} from "recharts";
import type { ChannelSlice } from "@/features/marketing/utils/marketing-drill-helpers";
import {
  formatMarketingCount,
  formatMarketingCurrency,
} from "../marketing-kpi-card";
import { MarketingChartCard } from "./marketing-chart-card";
import { marketingChartColor } from "./marketing-chart-colors";
import { percentOfTotal, formatCompactCount, formatCompactCurrency } from "./marketing-chart-config";
import { MarketingChartTooltip } from "./marketing-chart-tooltip";

type MarketingChannelDonutChartProps = {
  title: string;
  subtitle?: string;
  data: ChannelSlice[];
  valueType?: "currency" | "count";
  isLoading?: boolean;
};

type ActiveShapeProps = {
  cx: number;
  cy: number;
  innerRadius: number;
  outerRadius: number;
  startAngle: number;
  endAngle: number;
  fill: string;
};

function renderActiveShape(props: ActiveShapeProps) {
  const { cx, cy, innerRadius, outerRadius, startAngle, endAngle, fill } = props;
  return (
    <g>
      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius - 4}
        outerRadius={outerRadius + 8}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
        opacity={0.95}
      />
      <Sector
        cx={cx}
        cy={cy}
        innerRadius={innerRadius}
        outerRadius={outerRadius}
        startAngle={startAngle}
        endAngle={endAngle}
        fill={fill}
      />
    </g>
  );
}

export const MarketingChannelDonutChart = React.memo(
  function MarketingChannelDonutChart({
    title,
    subtitle,
    data,
    valueType = "currency",
    isLoading,
  }: MarketingChannelDonutChartProps) {
    const [activeIndex, setActiveIndex] = React.useState(0);
    const sorted = React.useMemo(
      () => [...data].sort((a, b) => b.value - a.value),
      [data],
    );
    const total = sorted.reduce((sum, row) => sum + row.value, 0);
    const formatValue = (value: number) =>
      valueType === "currency"
        ? formatMarketingCurrency(value)
        : formatMarketingCount(value);
    const formatCenterTotal = (value: number) =>
      valueType === "currency"
        ? formatCompactCurrency(value)
        : formatCompactCount(value);

    return (
      <MarketingChartCard
        title={title}
        subtitle={subtitle}
        isLoading={isLoading}
        isEmpty={!isLoading && total === 0}
        emptyMessage="No channel data"
        emptyDescription="Marketing channel breakdown appears when leads exist."
        chartHeight={320}
      >
        <div className="flex flex-col gap-4">
          <div className="relative h-[190px]">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={sorted}
                  dataKey="value"
                  nameKey="name"
                  innerRadius={58}
                  outerRadius={82}
                  paddingAngle={2}
                  stroke="none"
                  activeIndex={activeIndex}
                  activeShape={renderActiveShape}
                  onMouseEnter={(_, index) => setActiveIndex(index)}
                >
                  {sorted.map((_, index) => (
                    <Cell key={index} fill={marketingChartColor(index)} />
                  ))}
                </Pie>
                <Tooltip
                  content={
                    <MarketingChartTooltip
                      valueFormat={valueType === "currency" ? "currency" : "count"}
                    />
                  }
                />
              </PieChart>
            </ResponsiveContainer>
            <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center px-2 text-center">
              {sorted[activeIndex] ? (
                <span
                  className="text-[11px] font-bold leading-tight"
                  style={{ color: marketingChartColor(activeIndex) }}
                >
                  {sorted[activeIndex].name}
                </span>
              ) : null}
              <span className="mt-0.5 font-['Lexend'] text-sm font-extrabold leading-none tabular-nums text-text">
                {formatCenterTotal(total)}
              </span>
              {sorted[activeIndex] ? (
                <span className="mt-0.5 text-[10px] font-semibold text-gray-500">
                  {percentOfTotal(sorted[activeIndex].value, total).toFixed(1)}% of total
                </span>
              ) : null}
            </div>
          </div>

          <div className="max-h-[140px] space-y-2 overflow-y-auto pr-1">
            {sorted.map((row, index) => {
              const pct = percentOfTotal(row.value, total);
              return (
                <div
                  key={row.name}
                  className="rounded-xl border border-gray-100 bg-gray-50/60 px-3 py-2 transition-colors hover:bg-white"
                  onMouseEnter={() => setActiveIndex(index)}
                >
                  <div className="mb-1.5 flex items-center justify-between gap-2">
                    <div className="flex min-w-0 items-center gap-2">
                      <span
                        className="h-2.5 w-2.5 shrink-0 rounded-full"
                        style={{ backgroundColor: marketingChartColor(index) }}
                      />
                      <span className="truncate text-[11px] font-bold text-text">
                        {row.name}
                      </span>
                    </div>
                    <span className="shrink-0 text-[11px] font-extrabold tabular-nums text-text">
                      {formatValue(row.value)}
                    </span>
                  </div>
                  <div className="h-1.5 overflow-hidden rounded-full bg-gray-200/80">
                    <div
                      className="h-full rounded-full transition-all duration-300"
                      style={{
                        width: `${pct}%`,
                        backgroundColor: marketingChartColor(index),
                      }}
                    />
                  </div>
                  <div className="mt-1 text-right text-[10px] font-semibold text-gray-500">
                    {pct.toFixed(1)}% share
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </MarketingChartCard>
    );
  },
);
