/**
 * Bottom sheet for reassigning a duty to another user. Uses design tokens and safe area.
 */

"use client";

import type { DutyWithUser } from "@/types";
import type { UserForAdmin } from "@/lib/api";
import { localDateString, formatHHMM } from "@/lib/date-utils";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
  SheetFooter,
} from "@/components/ui/sheet";
import { cn } from "@/lib/utils";

export interface ReassignSheetProps {
  /** Whether the sheet is open (and not in exiting state). */
  open: boolean;
  /** Selected duty to reassign; when null, content may still render with previous duty during close. */
  selectedDuty: DutyWithUser | null;
  /** Current selected user id for the select. */
  selectedUserId: number | "";
  /** Called when user changes selection. */
  setSelectedUserId: (value: number | "") => void;
  /** Users to show in the dropdown (role_id 1 or 2). */
  users: UserForAdmin[];
  /** Reassign request in progress. */
  saving: boolean;
  /** i18n key for error message from last reassign attempt; null when no error. */
  reassignErrorKey: string | null;
  /** Called when user confirms reassign. */
  onReassign: () => void;
  /** Called when user requests close (start close animation). */
  onRequestClose: () => void;
  /** Called when close animation ends (clear state). */
  onCloseAnimationEnd: () => void;
  /** Translation function. */
  t: (key: string, params?: Record<string, string>) => string;
}

export function ReassignSheet({
  open,
  selectedDuty,
  selectedUserId,
  setSelectedUserId,
  users,
  saving,
  reassignErrorKey,
  onReassign,
  onRequestClose,
  onCloseAnimationEnd,
  t,
}: ReassignSheetProps) {
  return (
    <Sheet open={open} onOpenChange={(isOpen) => !isOpen && onRequestClose()}>
      <SheetContent
        side="bottom"
        className="flex max-h-[85vh] flex-col rounded-t-2xl bg-[var(--surface)] p-0 pt-3"
        overlayClassName="backdrop-blur-md"
        showCloseButton={false}
        onCloseAnimationEnd={onCloseAnimationEnd}
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <div className="relative min-h-0 flex-1 overflow-y-auto px-4">
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="absolute top-2 right-2 h-8 w-8 text-muted hover:text-[var(--text)] rounded-lg"
            onClick={onRequestClose}
            aria-label={t("day_detail.close")}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="18"
              height="18"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden
            >
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </Button>
          <div
            className="w-10 h-1 rounded-full bg-[var(--handle-bg)] mx-auto mb-2"
            aria-hidden
          />
          <SheetHeader className="p-0">
            <SheetTitle>{t("admin.reassign_duty")}</SheetTitle>
            <SheetDescription>{t("admin.select_user")}</SheetDescription>
          </SheetHeader>
          {selectedDuty && (
            <div className="flex flex-col gap-4 pt-2 pb-4">
              <p className="text-sm text-muted-foreground">
                {localDateString(new Date(selectedDuty.start_at))}{" "}
                {formatHHMM(selectedDuty.start_at)} – {formatHHMM(selectedDuty.end_at)}
              </p>
              <p className="text-xs text-muted-foreground">
                {t("admin.current_assignee")}: {selectedDuty.full_name}
              </p>
              {users.length === 0 ? (
                <p className="text-sm text-muted-foreground">
                  {t("admin.no_users_for_assign")}
                </p>
              ) : (
                <div
                  className="flex flex-col gap-1 max-h-[40vh] overflow-y-auto rounded-lg border border-border py-1"
                  role="radiogroup"
                  aria-label={t("admin.select_user")}
                >
                  {users.map((u) => {
                    const isCurrent = u.id === selectedDuty.user_id;
                    const isSelected = selectedUserId === u.id;
                    return (
                      <button
                        key={u.id}
                        type="button"
                        role="radio"
                        aria-checked={isSelected}
                        disabled={saving}
                        onClick={() => setSelectedUserId(u.id)}
                        className={cn(
                          "flex flex-col items-start gap-0.5 rounded-md px-3 py-2.5 text-left text-sm transition-colors",
                          "hover:bg-[var(--surface-hover)] focus-visible:outline-accent focus-visible:ring-2 focus-visible:ring-accent",
                          isCurrent && "bg-[var(--surface-today-tint)]",
                          isSelected && "ring-2 ring-accent ring-inset"
                        )}
                      >
                        <span className="font-medium">
                          {u.full_name}
                          {isCurrent && (
                            <span className="ml-2 text-xs text-muted-foreground font-normal">
                              ({t("admin.current_assignee")})
                            </span>
                          )}
                        </span>
                        {u.username && (
                          <span className="text-xs text-muted-foreground">@{u.username}</span>
                        )}
                      </button>
                    );
                  })}
                </div>
              )}
              {reassignErrorKey && (
                <p id="admin-reassign-error" className="text-sm text-destructive" role="alert">
                  {t(reassignErrorKey)}
                </p>
              )}
            </div>
          )}
        </div>
        <SheetFooter className="flex-shrink-0 flex-row justify-end gap-2 border-t border-border bg-[var(--surface)] px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]">
          <Button
            onClick={onReassign}
            disabled={
              saving ||
              selectedUserId === "" ||
              selectedUserId === selectedDuty?.user_id ||
              users.length === 0
            }
            aria-describedby={reassignErrorKey ? "admin-reassign-error" : undefined}
          >
            {saving ? t("loading") : t("admin.save")}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  );
}
