import * as React from 'react'
import * as cx from 'classnames'
import { StylableComponent } from '../theme'
import { Row } from '../flex'
import { Column } from '../flex'
import { List, ListItem } from '../list'
import { Spinner } from '../spinner'
import { TextInput } from '../text-input'
import { WebFormField } from '../form-field'
import { TextSearchProps, TextSearchComponentProps } from './interfaces'
import { AbstractFormField } from '../form-field'
import { shortID } from '../utils'

const styles = require('../../../src/components/form-field/styles.scss')

export class TextSearch extends StylableComponent<TextSearchComponentProps> {
    public render(): JSX.Element {
        const { name, placeholder } = this.props
        return (
            <Column className={styles.searchContainer}>
                <Row>
                    {this.renderInput()}
                    {this.renderSpinner()}
                </Row>
                {this.renderSearchResults()}
            </Column>
        )
    }

    private renderInput(): any {
        // todo
        return null
    }

    private renderSpinner(): JSX.Element {
        return <Spinner visible={this.props.loading} />
    }

    private renderSearchResults(): JSX.Element | null {
        if (!this.props.dropdownOpen) return null
        return (
            <List
                className={styles.resultsContainer}>
                {this.props.searchResults.map(o =>
                    <ListItem
                        key={shortID()}
                        onClick={this.setSelected(o)}>
                        {o.suggestion}
                    </ListItem>,
                )}
            </List>
        )
    }

    private setSelected = (o: any) => () => {
        this.props.setSelected(o)
    }

    private classNames(field: AbstractFormField<string>) {
        return cx(
            this.props.className,
            styles.inputContainer,
            {
                [styles.focus]: this.props.isFocused,
                [styles.success]: field.valid,
                [styles.error]: field.errors.length > 0 || (field.dirty && !field.valid),
            },
        )
    }
}
