/**
 * Admin page: list duties for the month and reassign duty to another user.
 * Visible only to admins (link shown on calendar when GET /api/admin/me returns is_admin).
 * Logic and heavy UI live in components/admin (useAdminPage, AdminDutyList, ReassignSheet).
 */

"use client";

import { useAdminPage, AdminDutyList, ReassignSheet } from "@/components/admin";
import { useTranslation } from "@/i18n/use-translation";
import { AccessDeniedScreen } from "@/components/states/AccessDeniedScreen";
import { LoadingState } from "@/components/states/LoadingState";
import { ErrorState } from "@/components/states/ErrorState";
import { Button } from "@/components/ui/button";
import { ChevronLeft as ChevronLeftIcon, ChevronRight as ChevronRightIcon } from "lucide-react";

const PAGE_WRAPPER_CLASS =
  "content-safe mx-auto flex min-h-[var(--tg-viewport-stable-height,100vh)] w-full max-w-[var(--max-width-app)] flex-col bg-background px-3 pb-6";

export default function AdminPage() {
  const { t, monthName } = useTranslation();
  const admin = useAdminPage();

  if (!admin.isAllowed) {
    return (
      <div className={PAGE_WRAPPER_CLASS}>
        <AccessDeniedScreen primaryAction="reload" />
      </div>
    );
  }

  if (admin.adminCheckComplete === null) {
    return (
      <div className={PAGE_WRAPPER_CLASS}>
        <div className="py-4 flex flex-col items-center gap-2">
          <LoadingState />
          <p className="text-sm text-muted-foreground">{t("admin.loading_users")}</p>
        </div>
      </div>
    );
  }

  if (admin.adminAccessDenied) {
    return (
      <div className={PAGE_WRAPPER_CLASS}>
        <div className="flex flex-col gap-4 py-6">
          <p className="text-muted-foreground">
            {admin.adminAccessDeniedDetail ?? t("admin.access_denied")}
          </p>
        </div>
      </div>
    );
  }

  const month = admin.adminMonth.getMonth();
  const year = admin.adminMonth.getFullYear();

  return (
    <div className={PAGE_WRAPPER_CLASS}>
      <header className="sticky top-0 z-10 flex flex-col items-center border-b bg-[var(--header-bg)] py-3">
        <div className="flex w-full items-center justify-between px-1">
          <Button
            type="button"
            variant="secondary"
            size="icon"
            className="size-10 rounded-[10px] bg-surface text-accent hover:bg-[var(--surface-hover)] focus-visible:outline-accent active:scale-95 disabled:opacity-50"
            aria-label={t("nav.prev_month")}
            disabled={admin.loading}
            onClick={admin.onPrevMonth}
          >
            <ChevronLeftIcon className="size-5" aria-hidden />
          </Button>
          <h1
            className="m-0 flex flex-col items-center justify-center gap-0 leading-none"
            aria-label={`${t("admin.title")}, ${monthName(month)} ${year}`}
          >
            <span className="text-xs font-normal leading-none text-muted">
              {year}
            </span>
            <span className="text-[1.1rem] font-semibold leading-tight sm:text-[1.25rem]">
              {monthName(month)}
            </span>
          </h1>
          <Button
            type="button"
            variant="secondary"
            size="icon"
            className="size-10 rounded-[10px] bg-surface text-accent hover:bg-[var(--surface-hover)] focus-visible:outline-accent active:scale-95 disabled:opacity-50"
            aria-label={t("nav.next_month")}
            disabled={admin.loading}
            onClick={admin.onNextMonth}
          >
            <ChevronRightIcon className="size-5" aria-hidden />
          </Button>
        </div>
        <p className="text-sm text-muted-foreground m-0 mt-1">
          {admin.loading ? "…" : t("admin.duties_count", { count: String(admin.dutyOnly.length) })}
        </p>
      </header>

      {admin.successMessage && (
        <p className="mt-3 text-sm text-[var(--duty)]" role="status" aria-live="polite">
          {admin.successMessage}
        </p>
      )}

      {admin.loading && (
        <div className="py-4 flex flex-col items-center gap-2">
          <LoadingState />
          <p className="text-sm text-muted-foreground">{t("admin.loading_users")}</p>
        </div>
      )}

      {admin.error && !admin.loading && (
        <ErrorState
          message={admin.error}
          onRetry={() => window.location.reload()}
          className="my-3"
        />
      )}

      {!admin.loading && !admin.error && (
        <div className="mt-3 flex flex-col gap-2">
          <p className="text-sm text-muted-foreground">
            {t("admin.reassign_duty")}: {t("admin.select_user")}
          </p>
          <AdminDutyList
            groups={admin.visibleGroups}
            hasMore={admin.hasMore}
            sentinelRef={admin.sentinelRef}
            onSelectDuty={admin.openReassign}
            t={t}
          />
        </div>
      )}

      <ReassignSheet
        open={!admin.sheetExiting && admin.selectedDuty !== null}
        selectedDuty={admin.selectedDuty}
        selectedUserId={admin.selectedUserId}
        setSelectedUserId={admin.setSelectedUserId}
        users={admin.usersForSelect}
        saving={admin.saving}
        reassignErrorKey={admin.reassignErrorKey}
        onReassign={admin.handleReassign}
        onRequestClose={admin.requestCloseSheet}
        onCloseAnimationEnd={admin.closeReassign}
        t={t}
      />
    </div>
  );
}
