"use client";

import {
  Bar,
  BarChart,
  Cell,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Card } from "@/components/ui/card";
import { formatInteger } from "@/lib/utils";

type Row = {
  month_start: string;
  total_emails_sent: number;
};

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

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

function monthTooltipLabel(value: string) {
  return new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric" }).format(
    new Date(value),
  );
}

function toMonthBounds(monthStart: string) {
  const startDate = new Date(`${monthStart}T00:00:00Z`);
  if (Number.isNaN(startDate.getTime())) {
    return null;
  }

  const year = startDate.getUTCFullYear();
  const monthIndex = startDate.getUTCMonth();
  const endDate = new Date(Date.UTC(year, monthIndex + 1, 0));

  return {
    from: `${year}-${String(monthIndex + 1).padStart(2, "0")}-01`,
    to: `${endDate.getUTCFullYear()}-${String(endDate.getUTCMonth() + 1).padStart(2, "0")}-${String(
      endDate.getUTCDate(),
    ).padStart(2, "0")}`,
  };
}

export function MonthlySendsChart({
  rows,
  selectedFilters,
  selectedMonth,
  emphasized,
}: {
  rows: Row[];
  selectedFilters: SelectedFilters;
  selectedMonth?: string;
  emphasized?: boolean;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  function applyMonthFilter(monthStart: string) {
    const bounds = toMonthBounds(monthStart);
    if (!bounds) return;

    const params = new URLSearchParams(searchParams.toString());
    params.set("from", bounds.from);
    params.set("to", bounds.to);
    params.set("month", monthStart.slice(0, 7));

    if (selectedFilters.country) {
      params.set("country", selectedFilters.country);
    }
    if (selectedFilters.brand) {
      params.set("brand", selectedFilters.brand);
    }
    if (selectedFilters.scope) {
      params.set("scope", selectedFilters.scope);
    }

    router.replace(`${pathname}?${params.toString()}`, { scroll: false });
  }

  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">Monthly Email Sends</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 monthly data yet. Upload an Excel file to populate this chart.</p>
        </div>
      </Card>
    );
  }

  return (
    <Card className={`h-[320px] min-w-0 bg-[linear-gradient(160deg,#ffffff_0%,#f4f9ff_100%)] ${emphasized ? "ring-2 ring-[#2663AC]/20" : ""}`}>
      <div className="flex flex-wrap items-start justify-between gap-2">
        <h3 className="min-w-0 break-words text-sm font-semibold text-slate-900">Monthly VEEVA Email Sends</h3>
        <p className="text-xs text-slate-500">Click a month bar to filter</p>
      </div>
      <div
        className="mt-4 h-[250px] min-w-0"
        onMouseDownCapture={(event) => event.preventDefault()}
      >
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={rows}
            barCategoryGap="28%"
            barGap={4}
            accessibilityLayer={false}
          >
            <defs>
              <linearGradient id="sendsFill" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#2663AC" />
                <stop offset="100%" stopColor="#7EA9DA" />
              </linearGradient>
              <linearGradient id="sendsFocusFill" 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" />
            <XAxis dataKey="month_start" tickFormatter={monthLabel} stroke="#64748b" fontSize={12} />
            <YAxis stroke="#64748b" fontSize={12} />
            <Tooltip
              cursor={false}
              formatter={(value) => [formatInteger(Number(value ?? 0)), "Emails Sent"]}
              labelFormatter={(label) => monthTooltipLabel(String(label))}
              contentStyle={{
                backgroundColor: "#ffffff",
                border: "1px solid #d1dbe8",
                borderRadius: "12px",
                boxShadow: "0 14px 28px -22px rgba(23,57,102,0.8)",
              }}
            />
            <Bar
              dataKey="total_emails_sent"
              radius={[8, 8, 0, 0]}
              activeBar={false}
              cursor="pointer"
              stroke="none"
              strokeWidth={0}
              maxBarSize={56}
              onClick={(data: { payload?: { month_start?: string } }) =>
                applyMonthFilter(String(data?.payload?.month_start ?? ""))
              }
            >
              {rows.map((row) => (
                <Cell
                  key={row.month_start}
                  fill={selectedMonth === row.month_start.slice(0, 7) ? "url(#sendsFocusFill)" : "url(#sendsFill)"}
                  stroke="none"
                  strokeWidth={0}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </Card>
  );
}
