// @flow
import * as React from 'react';

import {
	Col,
	Input,
	FormGroup,
} from 'reactstrap';

import ValidSchemaBadge from './ValidSchemaBadge.jsx';
import DeleteInputBtn from './DeleteInputBtn.jsx';
import CacheInput from './CacheInput.jsx';

type Props = {
	name: string,
	type: string,
	types: string[],
	typeTitles?: string[],
	existingFields: string[],
	nameUpdateFunc: (string) => any,
	typeUpdateFunc: (string) => any,
	nameValidateFunc?: (string) => boolean | React.Node,
	deleteFunc: (any) => any,
	children?: React.Node,
	placeholder?: string,
};

export const DupErr = ({ }: {}) => <span> Each field must have a unique name </span>;

class TypedField extends React.PureComponent<Props> {
	constructor(props: Props){
		super(props);
	}

	render = () => (
		<FormGroup row>
			<Col sm='6'>
				<CacheInput
					type='text'
					placeholder={this.props.placeholder || 'Name...'}
					value={this.props.name}
					onChange={(e) => this.props.nameUpdateFunc(e.target.value)}
					validateFunc={(str) => {
						if(this.props.existingFields.includes(str))
							return <DupErr />;
						if(this.props.nameValidateFunc)
							return this.props.nameValidateFunc(str);
						return true;
					}}
					fieldTest
				>
					<DeleteInputBtn deleteFunc={this.props.deleteFunc} />
				</CacheInput>
			</Col>
			<Col>
				<Input
					type='select'
					className='custom-select'
					value={this.props.type}
					onChange={e => this.props.typeUpdateFunc(e.target.value)}
				>
					<option disabled value=''>Type...</option>
					{
						this.props.types.map((t, i) => (
							<option key={i} value={t}>{Array.isArray(this.props.typeTitles) ? this.props.typeTitles[i] : (t === 'object' ? 'dict' : t)}</option>
						))
					}
				</Input>
			</Col>
			{ this.props.children }
		</FormGroup>
	);
}

export default TypedField;
