"use client";

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

interface WordCloudProps {
  words: WordFrequency[];
}

export function WordCloud({ words }: WordCloudProps) {
  if (words.length === 0) {
    return (
      <p className="py-8 text-center text-sm text-muted">
        No text responses to analyze.
      </p>
    );
  }

  const max = words[0]?.count ?? 1;
  const top = words.slice(0, 8).map((w) => ({
    ...w,
    display: w.word.length > 16 ? `${w.word.slice(0, 14)}…` : w.word,
  }));

  return (
    <div className="grid gap-6 lg:grid-cols-2 lg:items-start">
      <div className="h-[220px] w-full sm:h-[250px]">
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            layout="vertical"
            data={top}
            margin={{ top: 4, right: 16, left: 8, bottom: 4 }}
          >
            <CartesianGrid {...chartTheme.cartesianGrid} horizontal={false} />
            <XAxis type="number" allowDecimals={false} {...chartTheme.xAxis} />
            <YAxis
              type="category"
              dataKey="display"
              width={96}
              {...chartTheme.yAxis}
            />
            <Tooltip
              {...chartTheme.tooltip}
              formatter={(value, _name, item) => [
                `${value} mentions`,
                String(item?.payload?.word ?? "Word"),
              ]}
            />
            <Bar
              dataKey="count"
              name="Mentions"
              fill={CHART_COLORS.primary}
              radius={[0, 4, 4, 0]}
              barSize={16}
            />
          </BarChart>
        </ResponsiveContainer>
      </div>

      <div className="flex min-h-[180px] flex-wrap items-center justify-center gap-x-4 gap-y-2 rounded-lg border border-border bg-bg px-4 py-6">
        {words.map((w, i) => {
          const ratio = w.count / max;
          const size = 13 + ratio * 16;
          const color =
            i % 3 === 0
              ? CHART_COLORS.primary
              : i % 3 === 1
                ? CHART_COLORS.accent
                : CHART_COLORS.muted;

          return (
            <span
              key={w.word}
              title={`${w.count} mentions`}
              style={{
                fontSize: size,
                color,
                fontWeight: ratio > 0.6 ? 800 : ratio > 0.35 ? 700 : 600,
              }}
            >
              {w.word}
            </span>
          );
        })}
      </div>
    </div>
  );
}
