"use client";

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from "recharts";
import { chartTheme, npsBarColor } from "@/config/chart-theme";
import type { NpsDistributionPoint } from "@/types/analytics";
import { cn } from "@/lib/utils/cn";

interface NpsChartProps {
  distribution: NpsDistributionPoint[];
  npsScore: number;
}

function npsLabel(score: number): { text: string; className: string } {
  if (score >= 50) return { text: "Excellent", className: "text-success bg-success-bg" };
  if (score >= 30) return { text: "Great", className: "text-success bg-success-bg" };
  if (score >= 0) return { text: "Okay", className: "text-warning bg-warning-bg" };
  return { text: "Needs work", className: "text-danger bg-danger-bg" };
}

export function NpsChart({ distribution, npsScore }: NpsChartProps) {
  if (distribution.every((d) => d.count === 0)) {
    return (
      <p className="py-8 text-center text-sm text-muted">No NPS responses yet.</p>
    );
  }

  const detractors = distribution
    .filter((d) => d.score <= 6)
    .reduce((s, d) => s + d.count, 0);
  const passives = distribution
    .filter((d) => d.score >= 7 && d.score <= 8)
    .reduce((s, d) => s + d.count, 0);
  const promoters = distribution
    .filter((d) => d.score >= 9)
    .reduce((s, d) => s + d.count, 0);
  const total = detractors + passives + promoters || 1;
  const verdict = npsLabel(npsScore);

  const buckets = [
    {
      label: "Detractors",
      hint: "0–6",
      count: detractors,
      color: "bg-danger",
      text: "text-danger",
    },
    {
      label: "Passives",
      hint: "7–8",
      count: passives,
      color: "bg-accent",
      text: "text-accent",
    },
    {
      label: "Promoters",
      hint: "9–10",
      count: promoters,
      color: "bg-success",
      text: "text-success",
    },
  ];

  return (
    <div>
      <div className="mb-5 flex flex-wrap items-center gap-4">
        <div
          className="flex h-[72px] w-[72px] flex-col items-center justify-center rounded-full border-[6px] border-primary bg-white"
          style={{
            borderColor:
              npsScore >= 30 ? "#16A34A" : npsScore >= 0 ? "#00A3E0" : "#DC2626",
          }}
        >
          <span className="font-mono text-xl font-extrabold leading-none text-navy">
            {npsScore}
          </span>
        </div>
        <div>
          <div className="text-xs font-semibold text-muted">Net Promoter Score</div>
          <span
            className={cn(
              "mt-1 inline-block rounded-full px-2.5 py-0.5 text-[11px] font-bold",
              verdict.className
            )}
          >
            {verdict.text}
          </span>
        </div>
      </div>

      <div className="mb-5 grid grid-cols-3 gap-2">
        {buckets.map((b) => (
          <div
            key={b.label}
            className="rounded-lg border border-border bg-bg px-3 py-2.5"
          >
            <div className="mb-1 flex items-center gap-1.5 text-[11px] font-bold text-muted">
              <span className={cn("h-2 w-2 rounded-full", b.color)} />
              {b.label}
              <span className="font-medium">({b.hint})</span>
            </div>
            <div className={cn("font-mono text-lg font-extrabold", b.text)}>
              {Math.round((b.count / total) * 100)}%
            </div>
            <div className="text-[11px] text-muted">{b.count} people</div>
          </div>
        ))}
      </div>

      <div className="h-[200px] w-full sm:h-[240px]">
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={distribution}
            margin={{ top: 8, right: 8, left: -12, bottom: 0 }}
          >
            <CartesianGrid {...chartTheme.cartesianGrid} />
            <XAxis dataKey="score" {...chartTheme.xAxis} />
            <YAxis allowDecimals={false} {...chartTheme.yAxis} />
            <Tooltip
              {...chartTheme.tooltip}
              formatter={(value) => [`${value} people`, "Score"]}
              labelFormatter={(label) => `Score ${label}`}
            />
            <Bar dataKey="count" name="Responses" radius={[5, 5, 0, 0]} maxBarSize={36}>
              {distribution.map((entry) => (
                <Cell key={entry.score} fill={npsBarColor(entry.score)} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
