"use client";

import { useTranslation } from "@/hooks/useTranslation";
import {
  PACKAGE_ICONS,
  PACKAGE_ICON_IDS,
  type PackageIconId,
} from "@/lib/constants/package-icons";
import { cn } from "@/lib/utils";

interface PackageIconPickerProps {
  /** The stored identifier, or "" for none */
  value: string;
  onChange: (value: string) => void;
  id?: string;
  disabled?: boolean;
}

/**
 * Picks the `icon` identifier stored on a wash package.
 *
 * The field is free text backend-side, but the identifier is only meaningful
 * to whoever renders it — so the options come from the frontend's own map
 * (`lib/constants/package-icons.ts`) rather than a text box that could be
 * typed into an identifier nothing knows how to draw.
 *
 * Selecting the active option again clears the field: `icon` is optional on
 * both backend DTOs, and there'd otherwise be no way back to "none".
 */
export function PackageIconPicker({
  value,
  onChange,
  id,
  disabled,
}: PackageIconPickerProps) {
  const { t } = useTranslation();

  return (
    <div
      id={id}
      role="radiogroup"
      aria-label={t("catalog.form.icon")}
      className="flex flex-wrap gap-2"
    >
      {PACKAGE_ICON_IDS.map((iconId: PackageIconId) => {
        const Icon = PACKAGE_ICONS[iconId];
        const selected = value === iconId;

        return (
          <button
            key={iconId}
            type="button"
            role="radio"
            aria-checked={selected}
            aria-label={t(`catalog.icons.${iconId}`)}
            title={t(`catalog.icons.${iconId}`)}
            disabled={disabled}
            onClick={() => onChange(selected ? "" : iconId)}
            className={cn(
              // The muted track and the app background resolve to the same hex,
              // so the selected chip is white-on-muted — never bg-background.
              "flex size-12 items-center justify-center rounded-[12px] border transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",
              selected
                ? "border-primary-blue bg-card text-primary-blue shadow-sm"
                : "border-input bg-muted text-secondary-text hover:text-main-text",
            )}
          >
            <Icon className="size-5" />
          </button>
        );
      })}
    </div>
  );
}
