"use client";

import {
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Card } from "@/components/ui/card";
import { formatPercent } from "@/lib/utils";

type Row = {
  month_start: string;
  open_rate: number;
  ctr: number;
};

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

export function RateTrendChart({ 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">Open Rate & CTR Trend</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 trend data yet. Import email events to see rate movement.</p>
        </div>
      </Card>
    );
  }

  return (
    <Card className="h-[320px] bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
      <h3 className="text-sm font-semibold text-slate-900">Open Rate & CTR Trend</h3>
      <div
        className="mt-4 h-[250px]"
        onMouseDownCapture={(event) => event.preventDefault()}
      >
        <ResponsiveContainer width="100%" height="100%">
          <LineChart 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}
              tickFormatter={(value) => `${Math.round(Number(value) * 100)}%`}
            />
            <Tooltip
              cursor={false}
              formatter={(value) => formatPercent(Number(value ?? 0))}
              labelFormatter={(label) => monthLabel(String(label))}
              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 === "open_rate" ? "Open Rate" : "CTR")}
            />
            <Line type="monotone" dataKey="open_rate" stroke="#2663AC" strokeWidth={2.6} dot={false} />
            <Line type="monotone" dataKey="ctr" stroke="#F7993A" strokeWidth={2.6} dot={false} />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </Card>
  );
}
