// @flow
import * as React from 'react';
import {
	Container,
	Modal, ModalBody, ModalHeader, ModalFooter,
	Button,
	Form,
} from 'reactstrap';

import { generateNewKey } from '@helpers';

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

type Props = {
	// func to close modal
	toggle: () => any,
	// is the modal active?
	active: boolean,
	currentName: string,
	usedNames: string[],
	saveNewName: (newName: string) => any,
};

type State = {
	newName: string,
};

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

	state = {
		newName: this.props.currentName,
	}

	componentDidUpdate = (prevProps: Props) => {
		if(this.props.currentName !== prevProps.currentName){
			this.setState({ newName: this.props.currentName });
		}
	}

	validateFunc = (str: string) => {
		if(str === this.props.currentName)
			return true;
		if(!this.props.usedNames.includes(str))
			return true;
		return <span>The group name must be unique across all block &amp; group names in the toolchain</span>;
	}

	saveNewName = () => {
		this.props.saveNewName(this.state.newName);
		this.props.toggle();
	}

	render = () => {
		return (
			<Modal
				isOpen={this.props.active}
				toggle={this.props.toggle}
				fade={true}
			>
				<ModalHeader toggle={this.props.toggle}>
					Rename Group { `"${ this.props.currentName }"` }
				</ModalHeader>
				<ModalBody>
					<Form
						onSubmit={this.saveNewName}
					>
						<CacheInput
							delay={0}
							autoFocus
							fieldTest
							value={this.state.newName}
							validateFunc={this.validateFunc}
							onChange={e => this.setState({ newName: e.target.value })}
						/>
					</Form>
				</ModalBody>
				<ModalFooter>
					<Button
						block
						onClick={this.saveNewName}
					>
						Save Changes
					</Button>
				</ModalFooter>
			</Modal>
		);
	}
}

export default RenameGroupModal;
