"use client";

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

type MonthlyRow = {
  month_start: string;
  total_emails_sent: number;
  open_rate: number;
  ctr: number;
};

type PieRow = {
  name: string;
  value: number;
  color: string;
};

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

export function EmailDeepDiveCharts({
  monthly,
  engagementPie,
  countryPie,
}: {
  monthly: MonthlyRow[];
  engagementPie: PieRow[];
  countryPie: PieRow[];
}) {
  return (
    <section className="space-y-4">
      <Card className="bg-[linear-gradient(160deg,#ffffff_0%,#f5faff_100%)]">
        <h3 className="text-sm font-semibold text-slate-900">Monthly Trend (Open Rate vs CTR)</h3>
        {monthly.length === 0 ? (
          <div className="mt-4 rounded-2xl border border-dashed border-slate-300 bg-white/80 px-4 py-5 text-sm text-slate-500">
            No monthly timeline available for this item.
          </div>
        ) : (
          <div
            className="mt-4 h-[280px]"
            onMouseDownCapture={(event) => event.preventDefault()}
          >
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={monthly} accessibilityLayer={false}>
                <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 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>

      <div className="grid gap-4 xl:grid-cols-2">
        <Card className="bg-[linear-gradient(160deg,#ffffff_0%,#f6fbff_100%)]">
          <h3 className="text-sm font-semibold text-slate-900">Engagement Mix</h3>
          <div className="mt-4 h-[260px]">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={engagementPie}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  innerRadius={58}
                  outerRadius={92}
                  paddingAngle={2}
                >
                  {engagementPie.map((entry) => (
                    <Cell key={entry.name} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip
                  formatter={(value) => formatInteger(Number(value ?? 0))}
                  contentStyle={{
                    backgroundColor: "#ffffff",
                    border: "1px solid #d1dbe8",
                    borderRadius: "12px",
                    boxShadow: "0 14px 28px -22px rgba(23,57,102,0.8)",
                  }}
                />
                <Legend />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </Card>

        <Card className="bg-[linear-gradient(160deg,#ffffff_0%,#f6fbff_72%,#fff8ef_100%)]">
          <h3 className="text-sm font-semibold text-slate-900">Country Distribution</h3>
          {countryPie.length === 0 ? (
            <p className="mt-3 text-sm text-slate-500">No country split available.</p>
          ) : (
            <div className="mt-4 h-[260px]">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={countryPie}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    innerRadius={54}
                    outerRadius={88}
                  >
                    {countryPie.map((entry) => (
                      <Cell key={entry.name} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(value) => formatInteger(Number(value ?? 0))}
                    contentStyle={{
                      backgroundColor: "#ffffff",
                      border: "1px solid #d1dbe8",
                      borderRadius: "12px",
                      boxShadow: "0 14px 28px -22px rgba(23,57,102,0.8)",
                    }}
                  />
                  <Legend />
                </PieChart>
              </ResponsiveContainer>
            </div>
          )}
        </Card>
      </div>
    </section>
  );
}
