"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";

import { Loading } from "@/components/ui/loading";
import { Loader } from "@/components/ui/loader";
import { SearchInput } from "@/components/ui/search-input";
import { useGetProfileQuery } from "@/api/endpoints/auth-api";
import {
  getFirstAccessiblePath,
  canViewAeReport,
  type PermissionSource,
} from "@/lib/permissions";
import { useAeReportData } from "@/lib/ae-report-data";

import { AeReportMonthPicker } from "./ae-report-month-picker";
import { AeReportTree } from "./ae-report-tree";
import { AeReportTreeSkeleton } from "./ae-report-tree-skeleton";

function currentYearMonth(): { year: number; month: number } {
  const now = new Date();
  return { year: now.getFullYear(), month: now.getMonth() + 1 };
}

export default function AeReportPage() {
  const router = useRouter();
  const { data: session } = useSession();
  const backendUser = (session as { backendUser?: PermissionSource } | null)?.backendUser;
  const { data: profile } = useGetProfileQuery();
  const permissionSource: PermissionSource = backendUser ?? profile ?? null;

  const allowed = React.useMemo(
    () => canViewAeReport(permissionSource),
    [permissionSource],
  );

  React.useEffect(() => {
    if (!permissionSource) return;
    if (!allowed) {
      router.replace(getFirstAccessiblePath(permissionSource));
    }
  }, [permissionSource, allowed, router]);

  const [{ year, month }, setPeriod] = React.useState(currentYearMonth);
  const [search, setSearch] = React.useState("");

  const { tree, isContentLoading, isRefreshing, loadingMessage } = useAeReportData(
    year,
    month,
  );

  const handlePeriodChange = (nextYear: number, nextMonth: number) => {
    setPeriod({ year: nextYear, month: nextMonth });
  };

  if (!permissionSource || !allowed) {
    return <Loading variant="api" layout="page" message="Checking access..." />;
  }

  const showEmptyPeriod =
    !isContentLoading && tree.divisions.length === 0 && !search.trim();

  return (
    <div className="flex flex-col h-full gap-5 p-1 sm:p-2 md:p-4 animate-in fade-in duration-500 overflow-hidden">
      <div className="flex flex-col gap-3 border-b border-white/40 pb-6">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div className="flex flex-col gap-1">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-[21px] font-extrabold text-text font-['Lexend'] tracking-tight">
                AE Report
              </h1>
              {isRefreshing ? (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-[#6C63FF]/10 px-2.5 py-0.5 text-[11px] font-semibold text-[#6C63FF]">
                  <Loader variant="circular-progress" size="sm" className="text-[#6C63FF]" />
                  Syncing
                </span>
              ) : null}
            </div>
            <p className="text-[12px] text-gray-600 font-medium font-['Lexend_Deca']">
              Division → Team → AE attainment. Click a row to expand.
            </p>
          </div>
          <AeReportMonthPicker year={year} month={month} onChange={handlePeriodChange} />
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <SearchInput
            placeholder="Search AEs by name…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            wrapperClassName="max-w-xs"
            disabled={isContentLoading}
          />
        </div>
      </div>

      <div className="flex-1 min-h-0 overflow-y-auto pr-1 pb-6 scrollbar-themed">
        {isContentLoading ? (
          <AeReportTreeSkeleton message={loadingMessage} />
        ) : showEmptyPeriod ? (
          <div className="flex min-h-[240px] w-full items-center justify-center rounded-[14px] border border-dashed border-muted-foreground/30 text-[13px] text-muted-foreground font-medium font-['Lexend_Deca']">
            No attainment data for this period.
          </div>
        ) : (
          <AeReportTree divisions={tree.divisions} search={search} />
        )}
      </div>
    </div>
  );
}
