"use client";

import { useMemo, useState } from "react";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { formatInteger, formatPercent } from "@/lib/utils";
import { cn } from "@/lib/utils";
import { formatCountryLabel, normalizeCountryCode } from "@/lib/countries";

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

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

type ViewMode = "country" | "brand";

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

type EntitySummary = {
  label: string;
  total_emails_sent: number;
  open_rate: number;
  ctr: number;
};

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

function sortByMonth(a: string, b: string) {
  return new Date(a).getTime() - new Date(b).getTime();
}

export function MonthlyBreakdowns({
  countryRows,
  brandRows,
}: {
  countryRows: CountryMonthRow[];
  brandRows: BrandMonthRow[];
}) {
  const [view, setView] = useState<ViewMode>("country");
  const [month, setMonth] = useState<string>("all");
  const [query, setQuery] = useState("");
  const [visibleLimit, setVisibleLimit] = useState(14);

  const monthOptions = useMemo(() => {
    const values = [...countryRows.map((row) => row.month_start), ...brandRows.map((row) => row.month_start)];
    return [...new Set(values)].sort(sortByMonth);
  }, [countryRows, brandRows]);

  const rows = useMemo<BreakdownRow[]>(() => {
    if (view === "country") {
      return countryRows.map((row) => ({
        month_start: row.month_start,
        label: normalizeCountryCode(row.country_code),
        total_emails_sent: row.total_emails_sent,
        open_rate: row.open_rate,
        ctr: row.ctr,
      }));
    }

    return brandRows.map((row) => ({
      month_start: row.month_start,
      label: row.brand,
      total_emails_sent: row.total_emails_sent,
      open_rate: row.open_rate,
      ctr: row.ctr,
    }));
  }, [view, countryRows, brandRows]);

  const filteredRows = useMemo(() => {
    const term = query.trim().toLowerCase();
    return rows
      .filter((row) => (month === "all" ? true : row.month_start === month))
      .filter((row) => (term ? row.label.toLowerCase().includes(term) : true))
      .sort((a, b) => {
        if (b.total_emails_sent !== a.total_emails_sent) {
          return b.total_emails_sent - a.total_emails_sent;
        }
        return sortByMonth(b.month_start, a.month_start);
      });
  }, [rows, month, query]);

  const totals = useMemo(() => {
    const totalSent = filteredRows.reduce((sum, row) => sum + Number(row.total_emails_sent ?? 0), 0);
    const weightedOpenNumerator = filteredRows.reduce(
      (sum, row) => sum + Number(row.total_emails_sent ?? 0) * Number(row.open_rate ?? 0),
      0,
    );
    const weightedCtrNumerator = filteredRows.reduce(
      (sum, row) => sum + Number(row.total_emails_sent ?? 0) * Number(row.ctr ?? 0),
      0,
    );

    return {
      rowCount: filteredRows.length,
      totalSent,
      openRate: totalSent > 0 ? weightedOpenNumerator / totalSent : 0,
      ctr: totalSent > 0 ? weightedCtrNumerator / totalSent : 0,
    };
  }, [filteredRows]);

  const topEntities = useMemo(() => {
    const grouped = new Map<string, { label: string; sent: number; opened: number; clicked: number }>();

    for (const row of filteredRows) {
      const key = row.label;
      const current = grouped.get(key) ?? { label: key, sent: 0, opened: 0, clicked: 0 };
      const sent = Number(row.total_emails_sent ?? 0);
      current.sent += sent;
      current.opened += sent * Number(row.open_rate ?? 0);
      current.clicked += sent * Number(row.ctr ?? 0);
      grouped.set(key, current);
    }

    return [...grouped.values()]
      .sort((a, b) => b.sent - a.sent)
      .slice(0, 6)
      .map((item): EntitySummary => ({
        label: item.label,
        total_emails_sent: item.sent,
        open_rate: item.sent > 0 ? item.opened / item.sent : 0,
        ctr: item.sent > 0 ? item.clicked / item.sent : 0,
      }));
  }, [filteredRows]);

  const visibleRows = filteredRows.slice(0, visibleLimit);
  const maxEntitySent = topEntities.reduce((max, item) => Math.max(max, item.total_emails_sent), 0);

  function handleSwitch(next: ViewMode) {
    setView(next);
    setVisibleLimit(14);
    setQuery("");
  }

  function resetFilters() {
    setMonth("all");
    setQuery("");
    setVisibleLimit(14);
  }

  return (
    <Card className="overflow-hidden bg-[linear-gradient(160deg,#ffffff_0%,#f6fbff_74%,#fff9f2_100%)] p-4 sm:p-5">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h3 className="text-base font-semibold text-slate-900">Breakdown Explorer</h3>
          <p className="mt-1 text-sm text-slate-500">One focused view at a time for faster scanning.</p>
        </div>
        <div className="inline-flex rounded-2xl border border-[#d8e4f3] bg-white p-1">
          {(["country", "brand"] as const).map((mode) => {
            const active = view === mode;
            return (
              <button
                key={mode}
                type="button"
                onClick={() => handleSwitch(mode)}
                className={cn(
                  "rounded-xl px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.12em] transition",
                  active
                    ? "bg-[#2663AC] text-white shadow-[0_10px_20px_-14px_rgba(38,99,172,0.9)]"
                    : "text-slate-600 hover:bg-[#eef5ff]",
                )}
              >
                {mode}
              </button>
            );
          })}
        </div>
      </div>

      <div className="mt-4 grid gap-2 sm:grid-cols-3">
        <div className="sm:col-span-1">
          <label className="mb-1 block px-1 caption text-[10px] uppercase tracking-[0.16em] text-slate-500">
            Month
          </label>
          <Select
            value={month}
            onChange={(event) => {
              setMonth(event.target.value);
              setVisibleLimit(14);
            }}
            className="h-10 rounded-xl text-sm"
          >
            <option value="all">All months</option>
            {monthOptions.map((item) => (
              <option key={item} value={item}>
                {monthLabel(item)}
              </option>
            ))}
          </Select>
        </div>

        <div className="sm:col-span-2">
          <label className="mb-1 block px-1 caption text-[10px] uppercase tracking-[0.16em] text-slate-500">
            Search {view === "country" ? "country code" : "brand"}
          </label>
          <Input
            value={query}
            onChange={(event) => {
              setQuery(event.target.value);
              setVisibleLimit(14);
            }}
            placeholder={view === "country" ? "ES, PT..." : "Abilify, Rexulti..."}
            className="h-10 rounded-xl text-sm"
          />
        </div>
      </div>

      <div className="mt-4 grid gap-2 sm:grid-cols-4">
        <div className="rounded-xl border border-[#dbe7f5] bg-white/90 px-3 py-2">
          <p className="caption text-[10px] uppercase tracking-[0.14em] text-slate-500">Rows</p>
          <p className="mt-0.5 text-lg font-bold text-slate-900">{formatInteger(totals.rowCount)}</p>
        </div>
        <div className="rounded-xl border border-[#dbe7f5] bg-white/90 px-3 py-2">
          <p className="caption text-[10px] uppercase tracking-[0.14em] text-slate-500">Sent</p>
          <p className="mt-0.5 text-lg font-bold text-slate-900">{formatInteger(totals.totalSent)}</p>
        </div>
        <div className="rounded-xl border border-[#dbe7f5] bg-white/90 px-3 py-2">
          <p className="caption text-[10px] uppercase tracking-[0.14em] text-slate-500">Open Rate</p>
          <p className="mt-0.5 text-lg font-bold text-[#2663AC]">{formatPercent(totals.openRate)}</p>
        </div>
        <div className="rounded-xl border border-[#dbe7f5] bg-white/90 px-3 py-2">
          <p className="caption text-[10px] uppercase tracking-[0.14em] text-slate-500">CTR</p>
          <p className="mt-0.5 text-lg font-bold text-[#F7993A]">{formatPercent(totals.ctr)}</p>
        </div>
      </div>

      {filteredRows.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 breakdown data in this filter range.
        </div>
      ) : (
        <div className="mt-4 grid gap-3 xl:grid-cols-[300px_minmax(0,1fr)]">
          <div className="min-w-0 rounded-2xl border border-[#dbe7f5] bg-white/90 p-3">
            <h4 className="text-sm font-semibold text-slate-900">
              Top {view === "country" ? "Countries" : "Brands"}
            </h4>
            <div className="mt-3 space-y-2.5">
              {topEntities.map((entity) => {
                const width =
                  maxEntitySent > 0
                    ? `${Math.max(8, Math.round((entity.total_emails_sent / maxEntitySent) * 100))}%`
                    : "8%";

                return (
                  <div key={entity.label}>
                    <div className="flex items-center justify-between gap-2 text-sm">
                      <p className="min-w-0 break-words font-semibold text-slate-800">
                        {view === "country" ? formatCountryLabel(entity.label) : entity.label}
                      </p>
                      <p className="text-slate-500">{formatInteger(entity.total_emails_sent)}</p>
                    </div>
                    <div className="mt-1 h-1.5 overflow-hidden rounded-full bg-slate-100">
                      <div
                        className="h-full rounded-full bg-[linear-gradient(90deg,#2663AC_0%,#6da0d8_60%,#F7993A_100%)]"
                        style={{ width }}
                      />
                    </div>
                    <p className="mt-1 text-xs text-slate-500">
                      Open {formatPercent(entity.open_rate)} · CTR {formatPercent(entity.ctr)}
                    </p>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="min-w-0 rounded-2xl border border-[#dbe7f5] bg-white/95">
            <div className="max-h-[380px] overflow-auto rounded-2xl">
              <table className="min-w-[560px] w-full text-left text-sm">
                <thead className="sticky top-0 z-10 bg-[linear-gradient(120deg,#f4f9ff_0%,#f9fcff_100%)] text-[11px] uppercase tracking-[0.14em] text-slate-500">
                  <tr>
                    <th className="px-3 py-2">Month</th>
                    <th className="px-3 py-2">{view === "country" ? "Country" : "Brand"}</th>
                    <th className="px-3 py-2">Sent</th>
                    <th className="px-3 py-2">Open Rate</th>
                    <th className="px-3 py-2">CTR</th>
                  </tr>
                </thead>
                <tbody>
                  {visibleRows.map((row) => (
                    <tr
                      key={`${row.month_start}-${row.label}`}
                      className="border-t border-[#e2ebf7] transition hover:bg-[#f4f9ff]"
                    >
                      <td className="px-3 py-2.5 text-slate-600">{monthLabel(row.month_start)}</td>
                      <td className="px-3 py-2.5 font-medium text-slate-800">
                        {view === "country" ? (
                          <span className="inline-flex rounded-full bg-[#edf4ff] px-2 py-0.5 text-xs text-[#2663AC]">
                            {formatCountryLabel(row.label)}
                          </span>
                        ) : (
                          <span className="break-words">{row.label}</span>
                        )}
                      </td>
                      <td className="px-3 py-2.5 text-slate-700">{formatInteger(row.total_emails_sent)}</td>
                      <td className="px-3 py-2.5 text-[#2663AC]">{formatPercent(row.open_rate)}</td>
                      <td className="px-3 py-2.5 text-[#F7993A]">{formatPercent(row.ctr)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-2 border-t border-[#e2ebf7] px-3 py-2.5">
              <p className="text-xs text-slate-500">
                Showing {Math.min(visibleRows.length, filteredRows.length)} of {formatInteger(filteredRows.length)} rows
              </p>
              <div className="flex items-center gap-2">
                {filteredRows.length > 14 ? (
                  <button
                    type="button"
                    onClick={() =>
                      setVisibleLimit((current) =>
                        current >= filteredRows.length ? 14 : Math.min(current + 14, filteredRows.length),
                      )
                    }
                    className="rounded-lg border border-[#d3e1f2] bg-white px-2.5 py-1 text-xs font-semibold text-[#2663AC] transition hover:bg-[#eef5ff]"
                  >
                    {visibleLimit >= filteredRows.length ? "Show Less" : "Show More"}
                  </button>
                ) : null}
                <button
                  type="button"
                  onClick={resetFilters}
                  className="rounded-lg border border-[#e4eaf2] bg-white px-2.5 py-1 text-xs font-semibold text-slate-600 transition hover:bg-slate-50"
                >
                  Clear
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}
