"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDiscriminatedUnionInputs = generateDiscriminatedUnionInputs;
const generator_1 = require("@postxl/generator");
function generateDiscriminatedUnionInputs({ type, field }) {
    const variants = Array.from(field.members.values())
        .map((variant) => `{ id: '${variant.type}', label: '${variant.label}' }`)
        .join(', ');
    const imports = new generator_1.ImportGenerator({ path: '' }).addImports({
        [(0, generator_1.toPackageName)('@postxl/utils')]: [(0, generator_1.toTypeName)('UnionOmit')],
        [(0, generator_1.toPackageName)('react')]: [(0, generator_1.toFunctionName)('useMemo')],
        [type.discriminatorType.location]: [type.discriminatorType.name],
        [(0, generator_1.toBackendModuleLocation)('@components/ui/select/select')]: [
            (0, generator_1.toClassName)('Select'),
            (0, generator_1.toClassName)('SelectContent'),
            (0, generator_1.toClassName)('SelectItem'),
            (0, generator_1.toClassName)('SelectTrigger'),
            (0, generator_1.toClassName)('SelectValue'),
        ],
    });
    return `
  ${imports.generate()}

  export interface Variant {
    id: ${type.discriminatorType.name};
    label: string;
  }

  export const variants = [ ${variants} ] as Variant[];

  export interface ${type.type.name}SelectProps
    extends UnionOmit<
      React.ComponentPropsWithoutRef<typeof Select>,
      'value' | 'onValueChange'
    > {
    value?: ${type.discriminatorType.name} | null;
    defaultValue?: ${type.discriminatorType.name};
    label?: (variant: Variant) => string;
    item?: (variant: Variant) => React.ReactNode;

    onValueChange: (value: ${type.discriminatorType.name}) => void;
  }

  export function ${type.type.name}Select(
    { value, label = (item) => item.label, item = label, children, ...delegated }: ${type.type.name}SelectProps,
  ) {
    const selected = useMemo(() => variants.find((variant) => variant.id === value) ?? null, [value]);

    return (
      <Select {...delegated} value={value ?? undefined}>
        {children ?? (
          <SelectTrigger>
            {selected ? label(selected) : <SelectValue />}
          </SelectTrigger>
        )}

        <SelectContent>
          {variants.map((variant) => (
            <SelectItem key={variant.id} value={variant.id}>
              {item?.(variant) ?? variant.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    )
  }
  `;
}
//# sourceMappingURL=inputs.generator.js.map