import {
  DEPARTMENT_OPTIONS,
  isKnownDepartmentWorkplace,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  cn,
} from '@ump/shared';

/** Radix Select cannot use empty string as a value; this stands for “no unit selected”. */
const EMPTY_VALUE = '__workplace_none__';

export type WorkplaceSelectProps = {
  value: string;
  onValueChange: (workplace: string) => void;
  disabled?: boolean;
  /** Merged into SelectTrigger (table cells use border-b-only styling). */
  className?: string;
};

/**
 * “Nơi công tác” — stores the Vietnamese unit name in form state (same as legacy free-text),
 * so DOCX / PDF pipelines need no mapping.
 */
export function WorkplaceSelect({ value, onValueChange, disabled, className }: WorkplaceSelectProps) {
  const hasOrphan =
    value.length > 0 && !isKnownDepartmentWorkplace(value);
  const selectValue = value.length === 0 ? EMPTY_VALUE : value;

  return (
    <Select
      value={selectValue}
      onValueChange={(v) => onValueChange(v === EMPTY_VALUE ? '' : v)}
      disabled={disabled}
    >
      <SelectTrigger
        className={cn(
          'h-9 border-0 border-b border-border rounded-none px-1 shadow-none focus:ring-0 focus:ring-offset-0',
          className,
        )}
      >
        <SelectValue placeholder="Chọn đơn vị" />
      </SelectTrigger>
      <SelectContent position="popper" className="max-h-[min(24rem,70vh)]">
        <SelectItem value={EMPTY_VALUE}>— Chọn đơn vị —</SelectItem>
        {hasOrphan ? (
          <SelectItem value={value} className="text-muted-foreground">
            {value} (không trong danh sách)
          </SelectItem>
        ) : null}
        {DEPARTMENT_OPTIONS.map((o) => (
          <SelectItem key={o.value} value={o.label}>
            {o.label}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
