/**
 * Admin duty list: visible duties with infinite-scroll sentinel. Presentational only.
 */

"use client";

import { useRouter } from "next/navigation";
import type { DutyWithUser } from "@/types";
import { localDateString, formatHHMM, dateKeyToDDMM } from "@/lib/date-utils";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

export interface AdminDutyGroup {
  dateKey: string;
  duties: DutyWithUser[];
}

/** Empty state when there are no duties: message and "Back to calendar" CTA. */
function AdminEmptyState({
  t,
}: {
  t: (key: string, params?: Record<string, string>) => string;
}) {
  const router = useRouter();
  return (
    <div className="flex flex-col items-center gap-4 py-8 text-center">
      <h2 className="text-[1.1rem] font-semibold leading-tight m-0">
        {t("admin.no_duties")}
      </h2>
      <p className="text-sm text-muted-foreground m-0 max-w-[280px]">
        {t("duty.none_this_month_hint")}
      </p>
      <Button
        type="button"
        variant="secondary"
        onClick={() => router.push("/")}
        className="bg-surface text-accent hover:bg-[var(--surface-hover)]"
      >
        {t("admin.back_to_calendar")}
      </Button>
    </div>
  );
}

export interface AdminDutyListProps {
  /** Duty groups by date (already sliced to visibleCount by parent). */
  groups: AdminDutyGroup[];
  /** Whether there are more items; when true, sentinel is rendered for intersection observer. */
  hasMore: boolean;
  /** Ref for the sentinel element (infinite scroll). */
  sentinelRef: React.RefObject<HTMLDivElement | null>;
  /** Called when user selects a duty to reassign. */
  onSelectDuty: (duty: DutyWithUser) => void;
  /** Translation function. */
  t: (key: string, params?: Record<string, string>) => string;
}

export function AdminDutyList({
  groups,
  hasMore,
  sentinelRef,
  onSelectDuty,
  t,
}: AdminDutyListProps) {
  if (groups.length === 0) {
    return <AdminEmptyState t={t} />;
  }

  const todayKey = localDateString(new Date());
  return (
    <div className="flex flex-col gap-3" role="list" aria-label={t("admin.list_aria")}>
      {groups.map(({ dateKey, duties }) => {
        const isToday = dateKey === todayKey;
        const dateLabel = isToday ? t("duty.today") : dateKeyToDDMM(dateKey);
        return (
          <section
            key={dateKey}
            className="flex flex-col gap-1.5"
            aria-label={t("admin.section_aria", { date: dateLabel })}
          >
            <p
              className={cn(
                "text-[0.75rem] font-medium text-muted m-0 pl-0.5",
                isToday && "border-l-[3px] border-l-today pl-2 text-[var(--section-header)]"
              )}
            >
              {dateLabel}
            </p>
            <ul className="flex flex-col gap-1.5 list-none m-0 p-0">
              {duties.map((duty) => {
                const dateStr = localDateString(new Date(duty.start_at));
                const timeStr = `${formatHHMM(duty.start_at)} – ${formatHHMM(duty.end_at)}`;
                return (
                  <li key={duty.id}>
                    <button
                      type="button"
                      onClick={() => onSelectDuty(duty)}
                      aria-label={t("admin.reassign_aria", {
                        date: dateStr,
                        time: timeStr,
                        name: duty.full_name,
                      })}
                      className={cn(
                        "w-full min-h-0 rounded-lg border border-l-[3px] bg-surface px-2.5 py-2 shadow-sm text-left text-sm transition-colors",
                        "hover:bg-[var(--surface-hover)] focus-visible:outline-accent flex flex-col gap-0.5",
                        isToday ? "border-l-today" : "border-l-duty"
                      )}
                    >
                      <span>
                        <span className="font-medium">{dateStr}</span>
                        <span className="mx-2 text-muted-foreground">·</span>
                        <span className="text-muted-foreground">{timeStr}</span>
                      </span>
                      <span>{duty.full_name}</span>
                    </button>
                  </li>
                );
              })}
            </ul>
          </section>
        );
      })}
      {hasMore && (
        <div ref={sentinelRef} className="h-2" data-sentinel aria-hidden="true" />
      )}
    </div>
  );
}
