"use client";

import dynamic from "next/dynamic";
import { Card } from "@/components/ui/card";

type ChartRow = {
  month_start: string;
  total_emails_sent?: number;
  total_thumbs_up?: number;
  total_thumbs_down?: number;
  open_rate: number;
  ctr: number;
};

type SelectedFilters = {
  from: string;
  to: string;
  country: string;
  brand: string;
  scope?: string;
};

const MonthlySendsChart = dynamic(
  () => import("@/components/charts/monthly-sends-chart").then((mod) => mod.MonthlySendsChart),
  {
    ssr: false,
    loading: () => (
      <Card className="h-[320px] animate-pulse bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <div />
      </Card>
    ),
  },
);

const RateTrendChart = dynamic(
  () => import("@/components/charts/rate-trend-chart").then((mod) => mod.RateTrendChart),
  {
    ssr: false,
    loading: () => (
      <Card className="h-[320px] animate-pulse bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <div />
      </Card>
    ),
  },
);

const MonthlySentimentChart = dynamic(
  () =>
    import("@/components/charts/monthly-sentiment-chart").then(
      (mod) => mod.MonthlySentimentChart,
    ),
  {
    ssr: false,
    loading: () => (
      <Card className="h-[320px] animate-pulse bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)]">
        <div />
      </Card>
    ),
  },
);

export function DashboardCharts({
  rows,
  selectedFilters,
  selectedMonth,
  activeMetric,
}: {
  rows: ChartRow[];
  selectedFilters: SelectedFilters;
  selectedMonth?: string;
  activeMetric?: "emails_sent" | "opened" | "total_opens" | "clicked" | "total_clicks" | "ctor";
}) {
  const highlightVolume = activeMetric === "emails_sent";
  const highlightRates =
    activeMetric === "opened" || activeMetric === "total_opens" || activeMetric === "clicked" || activeMetric === "total_clicks" || activeMetric === "ctor";

  return (
    <section className="grid gap-3 xl:grid-cols-3">
      <MonthlySendsChart
        rows={rows.map((row) => ({ ...row, total_emails_sent: row.total_emails_sent ?? 0 }))}
        selectedFilters={selectedFilters}
        selectedMonth={selectedMonth}
        emphasized={highlightVolume}
      />
      <RateTrendChart rows={rows} emphasized={highlightRates} />
      <MonthlySentimentChart
        rows={rows.map((row) => ({
          month_start: row.month_start,
          total_thumbs_up: row.total_thumbs_up ?? 0,
          total_thumbs_down: row.total_thumbs_down ?? 0,
        }))}
      />
    </section>
  );
}
