"use client";

import { useTranslations } from "next-intl";
import { INVENTORY_UNITS, isKnownInventoryUnit } from "@/lib/inventory-units";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";

const CUSTOM_VALUE = "__custom__";

type InventoryUnitFieldProps = {
  value: string;
  onChange: (unit: string) => void;
  id?: string;
};

export function InventoryUnitField({ value, onChange, id }: InventoryUnitFieldProps) {
  const t = useTranslations("inventory");
  const selectValue = isKnownInventoryUnit(value) ? value : CUSTOM_VALUE;
  const showCustom = selectValue === CUSTOM_VALUE;

  return (
    <div className="space-y-2">
      <LabeledField label={t("unit")} htmlFor={id}>
        <select
          id={id}
          className="flex h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
          value={selectValue}
          onChange={(e) => {
            const next = e.target.value;
            if (next === CUSTOM_VALUE) {
              onChange(value && !isKnownInventoryUnit(value) ? value : "");
            } else {
              onChange(next);
            }
          }}
        >
          {INVENTORY_UNITS.map((u) => (
            <option key={u.value} value={u.value}>
              {t(`units.${u.key}`)}
            </option>
          ))}
          <option value={CUSTOM_VALUE}>{t("unitCustom")}</option>
        </select>
      </LabeledField>
      {showCustom ? (
        <Input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={t("unitCustomPlaceholder")}
        />
      ) : null}
      <p className="text-[11px] leading-relaxed text-muted-foreground">{t("unitsHelp")}</p>
    </div>
  );
}
