import Link from "next/link";
import { getViewerContext } from "@/lib/auth";
import { fetchDashboardData } from "@/lib/queries/dashboard";
import { KpiCards, KpiHighlights } from "@/components/dashboard/kpi-cards";
import { DashboardCharts } from "@/components/dashboard/dashboard-charts";
import { RankedDocuments } from "@/components/dashboard/ranked-documents";
import { DocumentTable } from "@/components/dashboard/document-table";
import { DashboardFilters } from "@/components/dashboard/dashboard-filters";
import { MonthlyBreakdowns } from "@/components/dashboard/monthly-breakdowns";
import {
  getAllRegionCountries,
  getDashboardScopeForCountries,
  getRegionCodes,
  getRegionMembers,
} from "@/lib/regions";

function monthBounds(monthKey: string) {
  const [yearRaw, monthRaw] = monthKey.split("-");
  const year = Number(yearRaw);
  const month = Number(monthRaw);
  if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) return null;
  const endDate = new Date(Date.UTC(year, month, 0));
  return {
    from: `${year}-${String(month).padStart(2, "0")}-01`,
    to: `${endDate.getUTCFullYear()}-${String(endDate.getUTCMonth() + 1).padStart(2, "0")}-${String(
      endDate.getUTCDate(),
    ).padStart(2, "0")}`,
  };
}

function asMonthKey(from: string, to: string) {
  if (!from || !to) return null;
  const fromParts = from.split("-");
  const toParts = to.split("-");
  if (fromParts.length !== 3 || toParts.length !== 3) return null;
  const [fromYear, fromMonth, fromDay] = fromParts.map(Number);
  const [toYear, toMonth, toDay] = toParts.map(Number);
  if (fromYear !== toYear || fromMonth !== toMonth || fromDay !== 1) return null;
  const endDate = new Date(Date.UTC(fromYear, fromMonth, 0));
  if (toDay !== endDate.getUTCDate()) return null;
  return `${String(fromYear).padStart(4, "0")}-${String(fromMonth).padStart(2, "0")}`;
}

function monthLabel(monthKey: string) {
  const bounds = monthBounds(monthKey);
  if (!bounds) return monthKey;
  return new Intl.DateTimeFormat("en-GB", { month: "long", year: "numeric" }).format(
    new Date(`${bounds.from}T00:00:00Z`),
  );
}

export default async function DashboardPage({
  searchParams,
}: {
  searchParams: Promise<{
    from?: string;
    to?: string;
    country?: string;
    brand?: string;
    month?: string;
    scope?: string;
  }>;
}) {
  const viewer = await getViewerContext();
  const params = await searchParams;
  const regionCodes = getRegionCodes();
  const requestedScope = (params.scope ?? "").trim().toUpperCase();
  const affiliateScope =
    viewer.role === "affiliate" ? getDashboardScopeForCountries(viewer.allowedCountries) ?? "" : "";
  const activeScope =
    viewer.role === "admin"
      ? (regionCodes.includes(requestedScope) ? requestedScope : "")
      : affiliateScope;
  const scopeCountries = activeScope ? getRegionMembers(activeScope) : [];
  const adminCountryOptions =
    viewer.role === "admin" ? (activeScope ? getRegionMembers(activeScope) : getAllRegionCountries()) : undefined;

  const data = await fetchDashboardData(viewer, {
    from: params.from ?? "",
    to: params.to ?? "",
    country: params.country ?? "",
    brand: params.brand ?? "",
  }, scopeCountries, adminCountryOptions);

  const monthKeys = data.monthlySeries
    .map((row) => row.month_start.slice(0, 7))
    .filter((value, index, array) => array.indexOf(value) === index);

  const requestedMonth = (params.month ?? "").trim();
  const derivedMonth = asMonthKey(data.selectedFilters.from, data.selectedFilters.to);
  const activeMonth = monthKeys.includes(requestedMonth)
    ? requestedMonth
    : derivedMonth && monthKeys.includes(derivedMonth)
      ? derivedMonth
      : null;

  function monthHref(monthKey: string) {
    const bounds = monthBounds(monthKey);
    if (!bounds) return "/dashboard";
    const query = new URLSearchParams();
    query.set("from", bounds.from);
    query.set("to", bounds.to);
    query.set("month", monthKey);
    if (data.selectedFilters.country) query.set("country", data.selectedFilters.country);
    if (data.selectedFilters.brand) query.set("brand", data.selectedFilters.brand);
    if (activeScope) query.set("scope", activeScope);
    return `/dashboard?${query.toString()}`;
  }

  function clearMonthHref() {
    const query = new URLSearchParams();
    if (data.selectedFilters.country) query.set("country", data.selectedFilters.country);
    if (data.selectedFilters.brand) query.set("brand", data.selectedFilters.brand);
    if (activeScope) query.set("scope", activeScope);
    const serialized = query.toString();
    return serialized ? `/dashboard?${serialized}` : "/dashboard";
  }

  return (
    <>
      <section className="grid gap-2.5 xl:grid-cols-[minmax(0,1fr)_minmax(690px,0.96fr)] xl:items-start">
        <KpiHighlights kpis={data.kpis} className="xl:h-full" />
        <DashboardFilters
          selected={{ ...data.selectedFilters, scope: activeScope }}
          minDate={data.minAvailableDate}
          maxDate={data.maxAvailableDate}
          availableCountries={data.availableCountries}
          availableBrands={data.availableBrands}
          className="xl:w-full"
        />
      </section>

      {data.setupRequired ? (
        <div className="enter-fade flex flex-wrap gap-2" style={{ ["--enter-delay" as string]: "100ms" }}>
          <p className="rounded-full border border-amber-400/50 bg-amber-50/95 px-3 py-1 text-xs text-amber-700">
            Supabase env not configured in <code>.env.local</code>
          </p>
        </div>
      ) : null}

      <div className="enter-fade-up" style={{ ["--enter-delay" as string]: "120ms" }}>
        <KpiCards kpis={data.kpis} />
      </div>

      {activeMonth ? (
        <section className="enter-fade-up rounded-2xl border border-[#f1cfaa] bg-[linear-gradient(165deg,#fff8f0_0%,#fff1e2_100%)] px-4 py-3 shadow-[0_16px_24px_-20px_rgba(199,110,33,0.62)]">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div>
              <p className="caption text-[10px] uppercase tracking-[0.16em] text-[#b46820]">Month Focus</p>
              <p className="text-base font-semibold text-slate-900">
                Showing {monthLabel(activeMonth)}
              </p>
            </div>
            <div className="flex items-center gap-2">
              {(() => {
                const activeIndex = monthKeys.indexOf(activeMonth);
                const previousMonth = activeIndex > 0 ? monthKeys[activeIndex - 1] : null;
                const nextMonth = activeIndex >= 0 && activeIndex < monthKeys.length - 1 ? monthKeys[activeIndex + 1] : null;
                return (
                  <>
                    {previousMonth ? (
                      <Link
                        href={monthHref(previousMonth)}
                        className="inline-flex items-center gap-1 rounded-lg border border-[#e6bc8d] bg-white px-3 py-1.5 text-xs font-semibold text-[#a35e1c] transition hover:bg-[#fff7ee]"
                      >
                        <span aria-hidden="true">←</span>
                        Prev
                      </Link>
                    ) : null}
                    {nextMonth ? (
                      <Link
                        href={monthHref(nextMonth)}
                        className="inline-flex items-center gap-1 rounded-lg border border-[#e6bc8d] bg-white px-3 py-1.5 text-xs font-semibold text-[#a35e1c] transition hover:bg-[#fff7ee]"
                      >
                        Next
                        <span aria-hidden="true">→</span>
                      </Link>
                    ) : null}
                    <Link
                      href={clearMonthHref()}
                      className="rounded-lg border border-[#d7e3f2] bg-white px-3 py-1.5 text-xs font-semibold text-[#2663AC] transition hover:bg-[#f5faff]"
                    >
                      All Months
                    </Link>
                  </>
                );
              })()}
            </div>
          </div>
        </section>
      ) : null}

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-4 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "180ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between rounded-2xl border border-[#e3ebf7] bg-[linear-gradient(120deg,#f9fcff_0%,#f0f7ff_100%)] px-4 py-3 text-sm font-semibold text-slate-900 transition hover:border-[#cddff3]">
          Monthly Trend View
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="mt-4 overflow-hidden transition duration-300 group-open:opacity-100">
          <DashboardCharts
            rows={data.monthlySeries}
            selectedFilters={{ ...data.selectedFilters, scope: activeScope }}
            selectedMonth={activeMonth ?? undefined}
          />
        </div>
      </details>

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-4 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "220ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between rounded-2xl border border-[#e3ebf7] bg-[linear-gradient(120deg,#f9fcff_0%,#f0f7ff_100%)] px-4 py-3 text-sm font-semibold text-slate-900 transition hover:border-[#cddff3]">
          Country + Brand + Time Breakdowns
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="mt-4">
          <MonthlyBreakdowns
            countryRows={data.countryMonthBreakdown}
            brandRows={data.brandMonthBreakdown}
          />
        </div>
      </details>

      <section
        className="enter-fade-up space-y-4"
        style={{ ["--enter-delay" as string]: "260ms" }}
      >
        <RankedDocuments
          title={`Top VAE Email Performers (min sent ${data.rankingMinSent})`}
          rows={data.topDocuments}
          emptyMessage="Not enough volume to rank top performers."
          tone="top"
        />
        <RankedDocuments
          title={`Lowest VAE Email Performers (min sent ${data.rankingMinSent})`}
          rows={data.worstDocuments}
          emptyMessage="Not enough volume to rank low performers."
          tone="low"
        />
      </section>

      <details
        open
        className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-0 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
        style={{ ["--enter-delay" as string]: "300ms" }}
      >
        <summary className="flex cursor-pointer list-none items-center justify-between border-b border-slate-200 px-4 py-4 text-sm font-semibold text-slate-900">
          VEEVA Email Library
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
            <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
              <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
            </svg>
          </span>
        </summary>
        <div className="px-4 pb-4">
          <DocumentTable rows={data.documentTable} />
        </div>
      </details>

    </>
  );
}
