import type { ComponentChildren } from 'preact';
import { TextField, type TextFieldProps } from './TextField';

export function parseCsvValue(value: string): string[] {
  return String(value || '')
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
}

export function stringifyCsvValue(values: string[] | undefined): string {
  return (values ?? []).join(', ');
}

export type CsvFieldProps = Omit<TextFieldProps, 'value' | 'onValueChange' | 'right'> & {
  value?: string[];
  right?: ComponentChildren;
  onValueChange?: (value: string[], raw: string) => void;
};

export function CsvField({ value, onValueChange, ...props }: CsvFieldProps) {
  return (
    <TextField
      {...props}
      value={stringifyCsvValue(value)}
      onValueChange={(raw) => onValueChange?.(parseCsvValue(raw), raw)}
    />
  );
}
