"use client";

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

type Row = {
  month_start: string;
  clickstream_events: number;
  linked_events: number;
  unique_calls: number;
  unique_presentations: number;
};

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

const AXIS_PROPS = {
  stroke: "#94a3b8",
  fontSize: 11,
  tickLine: false,
  axisLine: false,
} as const;

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));
}

export function ClmDashboardCharts({ rows }: { rows: Row[] }) {
  const chartRows = rows.map((row) => ({
    ...row,
    label: monthLabel(row.month_start),
    labelLong: monthLong(row.month_start),
  }));

  return (
    <section className="grid gap-3 xl:grid-cols-3">
      <Card className="h-[320px] min-w-0 bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <p className="text-sm font-semibold text-slate-900">Monthly activity volume</p>
        <div className="mt-4 h-[250px] min-w-0" onMouseDownCapture={(e) => e.preventDefault()}>
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={chartRows} barCategoryGap="32%">
              <defs>
                <linearGradient id="clmBarBlue" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#2663AC" />
                  <stop offset="100%" stopColor="#7EA9DA" />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#dbe7f5" vertical={false} />
              <XAxis dataKey="label" {...AXIS_PROPS} />
              <YAxis {...AXIS_PROPS} />
              <Tooltip
                cursor={false}
                contentStyle={TOOLTIP_STYLE}
                labelFormatter={(_label, payload) =>
                  payload?.[0]?.payload?.labelLong ?? _label
                }
                formatter={(value) => [Number(value).toLocaleString(), "Events"]}
              />
              <Bar dataKey="clickstream_events" name="Events" fill="url(#clmBarBlue)" radius={[8, 8, 0, 0]} maxBarSize={52} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </Card>

      <Card className="h-[320px] min-w-0 bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <p className="text-sm font-semibold text-slate-900">Presentation-linked events by month</p>
        <div className="mt-4 h-[250px] min-w-0" onMouseDownCapture={(e) => e.preventDefault()}>
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={chartRows}>
              <CartesianGrid strokeDasharray="3 3" stroke="#dbe7f5" vertical={false} />
              <XAxis dataKey="label" {...AXIS_PROPS} />
              <YAxis {...AXIS_PROPS} />
              <Tooltip
                cursor={false}
                contentStyle={TOOLTIP_STYLE}
                labelFormatter={(_label, payload) =>
                  payload?.[0]?.payload?.labelLong ?? _label
                }
                formatter={(value, name) => [
                  Number(value).toLocaleString(),
                  name === "clickstream_events" ? "All tracked events" : "Events linked to a presentation",
                ]}
              />
              <Legend
                iconType="plainline"
                formatter={(value) =>
                  value === "clickstream_events" ? "All tracked events" : "Events linked to a presentation"
                }
                wrapperStyle={{ fontSize: 12 }}
              />
              <Line type="monotone" dataKey="clickstream_events" name="clickstream_events" stroke="#2663AC" strokeWidth={2.5} dot={false} activeDot={{ r: 4, strokeWidth: 0 }} />
              <Line type="monotone" dataKey="linked_events" name="linked_events" stroke="#F7993A" strokeWidth={2.5} dot={false} activeDot={{ r: 4, strokeWidth: 0 }} />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </Card>

      <Card className="h-[320px] min-w-0 bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <p className="text-sm font-semibold text-slate-900">Calls and presentations by month</p>
        <div className="mt-4 h-[250px] min-w-0" onMouseDownCapture={(e) => e.preventDefault()}>
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={chartRows} barCategoryGap="28%" barGap={3}>
              <defs>
                <linearGradient id="clmCallsBlue" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#2663AC" />
                  <stop offset="100%" stopColor="#7EA9DA" />
                </linearGradient>
                <linearGradient id="clmPresOrange" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#F7993A" />
                  <stop offset="100%" stopColor="#E98B2E" />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#dbe7f5" vertical={false} />
              <XAxis dataKey="label" {...AXIS_PROPS} />
              <YAxis {...AXIS_PROPS} />
              <Tooltip
                cursor={false}
                contentStyle={TOOLTIP_STYLE}
                labelFormatter={(_label, payload) =>
                  payload?.[0]?.payload?.labelLong ?? _label
                }
                formatter={(value, name) => [
                  Number(value).toLocaleString(),
                  name === "unique_calls" ? "Calls" : "Presentations",
                ]}
              />
              <Legend
                iconType="plainline"
                formatter={(value) => (value === "unique_calls" ? "Calls" : "Presentations")}
                wrapperStyle={{ fontSize: 12 }}
              />
              <Bar dataKey="unique_calls" name="unique_calls" fill="url(#clmCallsBlue)" radius={[8, 8, 0, 0]} maxBarSize={40} />
              <Bar dataKey="unique_presentations" name="unique_presentations" fill="url(#clmPresOrange)" radius={[8, 8, 0, 0]} maxBarSize={40} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </Card>
    </section>
  );
}
