"use client";

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

interface RatingChartProps {
  distribution: NpsDistributionPoint[];
  average: number;
}

function ratingColor(score: number, min: number, max: number): string {
  const span = Math.max(max - min, 1);
  const t = (score - min) / span;
  if (t <= 0.2) return CHART_COLORS.danger;
  if (t <= 0.4) return "#F59E0B";
  if (t <= 0.6) return CHART_COLORS.accent;
  if (t <= 0.8) return CHART_COLORS.primary;
  return CHART_COLORS.success;
}

function Stars({ value, max }: { value: number; max: number }) {
  const rounded = Math.round(value);
  return (
    <div className="flex gap-0.5 text-[18px] leading-none" aria-hidden>
      {Array.from({ length: max }, (_, i) => (
        <span
          key={i}
          className={i < rounded ? "text-warning" : "text-[#E2E8F0]"}
        >
          ★
        </span>
      ))}
    </div>
  );
}

export function RatingChart({ distribution, average }: RatingChartProps) {
  if (distribution.every((d) => d.count === 0)) {
    return (
      <p className="py-8 text-center text-sm text-muted">No ratings yet.</p>
    );
  }

  const total = distribution.reduce((sum, d) => sum + d.count, 0);
  const min = distribution[0]?.score ?? 1;
  const max = distribution[distribution.length - 1]?.score ?? 5;

  return (
    <div>
      <div className="mb-5 flex flex-wrap items-center gap-4">
        <div>
          <div className="font-mono text-[32px] font-extrabold leading-none text-navy">
            {average}
            <span className="ml-1 text-base font-semibold text-muted">
              / {max}
            </span>
          </div>
          <p className="mt-1 text-xs font-semibold text-muted">
            Average rating · {total} response{total === 1 ? "" : "s"}
          </p>
        </div>
        <Stars value={average} max={Math.min(max, 10)} />
      </div>

      <div className="h-[220px] w-full sm:h-[260px]">
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={distribution}
            margin={{ top: 8, right: 8, left: -12, bottom: 4 }}
          >
            <CartesianGrid {...chartTheme.cartesianGrid} />
            <XAxis
              dataKey="score"
              {...chartTheme.xAxis}
              tickFormatter={(v) => `${v}★`}
            />
            <YAxis allowDecimals={false} {...chartTheme.yAxis} />
            <Tooltip
              {...chartTheme.tooltip}
              formatter={(value) => [`${value} people`, "Chose"]}
              labelFormatter={(label) => `${label} star${label === 1 ? "" : "s"}`}
            />
            <Bar dataKey="count" name="Responses" radius={[6, 6, 0, 0]} maxBarSize={48}>
              {distribution.map((entry) => (
                <Cell
                  key={entry.score}
                  fill={ratingColor(entry.score, min, max)}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
