import React from 'react';
import {StyleProp, Text, TextStyle, TouchableWithoutFeedback, View} from 'react-native';
import {MaterialIcons as Icon} from '@expo/vector-icons';
import {WithTheme, WithThemeStyles} from '../style';
import {CheckboxPropsType} from './PropsType';
import CheckboxStyles, {CheckboxStyle} from './style';

export interface CheckboxProps extends CheckboxPropsType, WithThemeStyles<CheckboxStyle> {
    style?: StyleProp<TextStyle>;
}

export default class Checkbox extends React.Component<CheckboxProps, any> {
    static CheckboxItem: any;
    static AgreeItem: any;

    constructor(props: CheckboxProps, context: any) {
        super(props, context);

        this.state = {
            checked: props.checked || props.defaultChecked || false,
        };
    }

    UNSAFE_componentWillReceiveProps(nextProps: CheckboxProps): void {
        if (typeof nextProps.checked === 'boolean') {
            this.setState({
                checked: !!nextProps.checked,
            });
        }
    }

    handleClick = () => {
        if (this.props.disabled) {
            return;
        }
        const checked = !this.state.checked;
        if (!(typeof this.props.checked === 'boolean')) {
            this.setState({
                checked,
            });
        }
        if (this.props.onChange) {
            this.props.onChange({target: {checked}});
        }
    };

    render(): JSX.Element {
        const {style, disabled, children} = this.props;
        const checked = this.state.checked;
        return (
            <WithTheme themeStyles={CheckboxStyles} styles={this.props.styles}>
                {(styles, theme) => {
                    let icon;
                    if (checked) {
                        icon = disabled ? (
                            <Icon name="check" style={[styles.checkBoxChecked, style,{opacity: 0.5}]} />
                        ) : (
                            <Icon name="check" style={[styles.checkBoxChecked, style]} />
                        );
                    } else {
                        icon = disabled ? (
                            <Icon name="check" style={[styles.checkBox, style]} />
                        ) : (
                            <Icon name="check" style={[styles.checkBox, style]} />
                        );
                    }

                    return (
                        <TouchableWithoutFeedback onPress={this.handleClick}>
                            <View style={[styles.wrapper, {flexDirection: this.props.reverse ? 'row-reverse' : 'row'}]}>
                                {icon}
                                {typeof children === 'string' ? <Text style={styles.iconRight}>{this.props.children}</Text> : children}
                            </View>
                        </TouchableWithoutFeedback>
                    );
                }}
            </WithTheme>
        );
    }
}
