"use client";

import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { formatInteger, formatPercent } from "@/lib/utils";
import type { MonthlyDashboardRow } from "@/lib/types";

type MetricKey =
  | "emails_sent"
  | "opened"
  | "total_opens"
  | "clicked"
  | "total_clicks"
  | "ctor";

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

function monthLong(value: string) {
  return new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric" }).format(
    new Date(`${value}T00:00:00Z`),
  );
}

const TOOLTIP_STYLE = {
  backgroundColor: "#ffffff",
  border: "1px solid #d1dbe8",
  borderRadius: "12px",
  boxShadow: "0 14px 28px -22px rgba(23,57,102,0.8)",
};

type MetricConfig = {
  label: string;
  color: string;
  desc: string;
  formula: string;
  chartType: "bar" | "line";
  dataKey: string;
  isPercent: boolean;
  tooltipLabel: string;
};

const META: Record<MetricKey, MetricConfig> = {
  emails_sent: {
    label: "Emails Sent",
    color: "#F7993A",
    desc: "How many email sends went out each month.",
    formula: "Raw send count.",
    chartType: "bar",
    dataKey: "total_emails_sent",
    isPercent: false,
    tooltipLabel: "Emails sent",
  },
  opened: {
    label: "Opened",
    color: "#2663AC",
    desc: "Unique emails that were opened at least once in each month.",
    formula: "Unique opened emails, not repeated opens.",
    chartType: "bar",
    dataKey: "total_opened",
    isPercent: false,
    tooltipLabel: "Opened",
  },
  total_opens: {
    label: "Total Opens",
    color: "#2663AC",
    desc: "All open actions in each month, including repeat opens from the same email.",
    formula: "Includes repeated opens.",
    chartType: "bar",
    dataKey: "total_opens",
    isPercent: false,
    tooltipLabel: "Total opens",
  },
  clicked: {
    label: "Clicked",
    color: "#F7993A",
    desc: "Unique emails that generated at least one click in each month.",
    formula: "Unique clicked emails, not repeated clicks.",
    chartType: "bar",
    dataKey: "total_clicked",
    isPercent: false,
    tooltipLabel: "Clicked",
  },
  total_clicks: {
    label: "Total Clicks",
    color: "#F7993A",
    desc: "All click actions in each month, including repeat clicks from the same email.",
    formula: "Includes repeated clicks.",
    chartType: "bar",
    dataKey: "total_clicks",
    isPercent: false,
    tooltipLabel: "Total clicks",
  },
  ctor: {
    label: "Click To Open %",
    color: "#F7993A",
    desc: "How often opened emails went on to click in each month.",
    formula: "Clicks divided by opens.",
    chartType: "line",
    dataKey: "ctor",
    isPercent: true,
    tooltipLabel: "Click To Open %",
  },
};

export function KpiInlineChart({
  metric,
  rows,
  onClose,
}: {
  metric: MetricKey;
  rows: MonthlyDashboardRow[];
  onClose: () => void;
}) {
  const meta = META[metric];
  const gradientId = meta.chartType === "bar" ? "kpiBarGrad" : "kpiLineGrad";

  return (
    <div className="enter-fade-up overflow-hidden rounded-2xl border border-[#d8e4f3] bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)] shadow-[0_16px_32px_-24px_rgba(38,99,172,0.38)]">
      <div className="flex items-center justify-between border-b border-[#e5eef8] px-4 py-3">
        <div>
          <p className="caption text-[10px] uppercase tracking-[0.18em]" style={{ color: meta.color }}>
            Metric Breakdown
          </p>
          <p className="text-sm font-semibold text-slate-800">
            {meta.label}
          </p>
          <p className="mt-1 text-xs text-slate-500">
            {meta.desc} <span className="font-medium text-slate-700">{meta.formula}</span>
          </p>
        </div>
        <button
          type="button"
          onClick={onClose}
          className="inline-flex items-center gap-1.5 rounded-full border border-[#d8e4f3] bg-white px-3 py-1.5 text-xs font-semibold text-slate-500 transition hover:border-[#2663AC]/30 hover:text-[#2663AC]"
          aria-label="Hide breakdown"
        >
          <svg viewBox="0 0 20 20" className="h-3.5 w-3.5 fill-current" aria-hidden="true">
            <path d="M6.28 5.22a.75.75 0 0 0-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 1 0 1.06 1.06L10 11.06l3.72 3.72a.75.75 0 1 0 1.06-1.06L11.06 10l3.72-3.72a.75.75 0 0 0-1.06-1.06L10 8.94 6.28 5.22Z" />
          </svg>
          Hide
        </button>
      </div>

      <div className="h-[220px] px-2 py-4" onMouseDownCapture={(e) => e.preventDefault()}>
        <ResponsiveContainer width="100%" height="100%">
          {meta.chartType === "bar" ? (
            <BarChart data={rows} barCategoryGap="28%" accessibilityLayer={false}>
              <defs>
                <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={meta.color} />
                  <stop offset="100%" stopColor={meta.color} stopOpacity={0.6} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#dbe7f5" />
              <XAxis dataKey="month_start" tickFormatter={monthLabel} stroke="#64748b" fontSize={11} />
              <YAxis stroke="#64748b" fontSize={11} />
              <Tooltip
                cursor={false}
                formatter={(value) => [formatInteger(Number(value ?? 0)), meta.tooltipLabel]}
                labelFormatter={(label) => monthLong(String(label))}
                contentStyle={TOOLTIP_STYLE}
              />
              <Bar dataKey={meta.dataKey} radius={[6, 6, 0, 0]} maxBarSize={52} stroke="none">
                {rows.map((row) => (
                  <Cell key={row.month_start} fill={`url(#${gradientId})`} stroke="none" />
                ))}
              </Bar>
            </BarChart>
          ) : (
            <LineChart data={rows} accessibilityLayer={false}>
              <CartesianGrid strokeDasharray="3 3" stroke="#dbe7f5" />
              <XAxis dataKey="month_start" tickFormatter={monthLabel} stroke="#64748b" fontSize={11} />
              <YAxis
                stroke="#64748b"
                fontSize={11}
                tickFormatter={(v) => `${Math.round(Number(v) * 100)}%`}
              />
              <Tooltip
                cursor={false}
                formatter={(value) => [formatPercent(Number(value ?? 0)), meta.tooltipLabel]}
                labelFormatter={(label) => monthLong(String(label))}
                contentStyle={TOOLTIP_STYLE}
              />
              <Line
                type="monotone"
                dataKey={meta.dataKey}
                stroke={meta.color}
                strokeWidth={2.5}
                dot={{ fill: meta.color, r: 3, strokeWidth: 0 }}
                activeDot={{ r: 5, strokeWidth: 0 }}
              />
            </LineChart>
          )}
        </ResponsiveContainer>
      </div>
    </div>
  );
}
