import * as React from 'react'
import * as cx from 'classnames'
import { BaseFormField } from '../form-field'
import { Row } from '../flex'
import { Column } from '../flex'
import { ValidationIcon } from './validation-icon'

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

export abstract class WebFormField<T> extends BaseFormField<T> {

    /**
     * Initialize the field
     * this will also trigger the validation
     * but will not mark the field as dirty (only onFocus does that)
     */
    public componentDidMount() {
        // console.log('FORM FIELD DID MOUNT', this)
        this.init()

        if (this.props.autofocus) {
            this.field.focus()
        }
    }

    public render() {
        const { field, fullWidth, containerClassName, containerStyles } = this.props
        // console.log('RENDER FORM FIELD', this)

        // the field may not be initialized yet
        if (!field) return null

        return (
            <Column
                className={cx(styles.fieldset, containerClassName)}
                fullWidth={fullWidth}
                style={containerStyles}>
                <Row>
                    {this.renderField()}
                    {this.renderValidationIcon()}
                </Row>
                <Row align="flex-start" className={styles.errorText} fullWidth={fullWidth}>
                    {this.renderErrors()}
                </Row>
            </Column>
        )
    }

    public classNames(...args: string[]): string {
        const { valid, errors, focused, required } = this.props.field
        const res = cx(
            styles.field,
            ...args,
            this.props.className,
            {
                [styles.disabled]: this.props.disabled === true,
                [borderStyles.error]: !this.props.disabled && this.shouldShowErrors(),
                [borderStyles.success]: this.shouldShowValid(),
                [borderStyles.info]: !this.props.disabled && focused && !valid,
            },
        )
        // console.log('classnames', this.props, res)
        return res
    }

    private renderValidationIcon(): JSX.Element | null {
        if (!this.props.showValidationIcon) return null
        return <ValidationIcon valid={this.shouldShowValid()} error={this.shouldShowErrors()} />
    }
}
