"use client";

import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Card } from "@/components/ui/card";
import { formatInteger } from "@/lib/utils";

type Row = {
  month_start: string;
  total_thumbs_up: number;
  total_thumbs_down: number;
};

function monthLabel(value: string) {
  return new Intl.DateTimeFormat("en-GB", { month: "short", year: "2-digit" }).format(
    new Date(value),
  );
}

function monthTooltipLabel(value: string) {
  return new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric" }).format(
    new Date(value),
  );
}

export function MonthlySentimentChart({ rows }: { rows: Row[] }) {
  if (rows.length === 0) {
    return (
      <Card className="h-[320px] bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <h3 className="text-sm font-semibold text-slate-900">Monthly HCP Sentiment</h3>
        <div className="mt-4 flex h-[250px] items-center justify-center rounded-2xl border border-dashed border-slate-300 bg-slate-50">
          <p className="text-sm text-slate-500">No thumbs-up/down data yet for this filter range.</p>
        </div>
      </Card>
    );
  }

  return (
    <Card className="h-[320px] min-w-0 bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
      <h3 className="min-w-0 break-words text-sm font-semibold text-slate-900">Monthly HCP Sentiment</h3>
      <div className="mt-4 h-[250px] min-w-0" onMouseDownCapture={(event) => event.preventDefault()}>
        <ResponsiveContainer width="100%" height="100%">
          <BarChart data={rows} accessibilityLayer={false}>
            <CartesianGrid strokeDasharray="3 3" stroke="#dbe7f5" />
            <XAxis dataKey="month_start" tickFormatter={monthLabel} stroke="#64748b" fontSize={12} />
            <YAxis stroke="#64748b" fontSize={12} />
            <Tooltip
              cursor={false}
              labelFormatter={(label) => monthTooltipLabel(String(label))}
              formatter={(value, name) => [
                formatInteger(Number(value ?? 0)),
                name === "total_thumbs_up" ? "Thumbs Up" : "Thumbs Down",
              ]}
              contentStyle={{
                backgroundColor: "#ffffff",
                border: "1px solid #d1dbe8",
                borderRadius: "12px",
                boxShadow: "0 14px 28px -22px rgba(23,57,102,0.8)",
              }}
            />
            <Legend
              iconType="plainline"
              formatter={(value) => (value === "total_thumbs_up" ? "Positive" : "Negative")}
            />
            <Bar dataKey="total_thumbs_up" name="total_thumbs_up" fill="#E7A46E" radius={[6, 6, 0, 0]} />
            <Bar dataKey="total_thumbs_down" name="total_thumbs_down" fill="#6E9FD3" radius={[6, 6, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </Card>
  );
}
