import { ChangeEvent, Component, FormEvent, ReactNode } from 'react';
import * as React from 'react';
import { AmplitudeEvents } from '../../events/amplitudeEvents';
import nsLogo from '../../images/ns-logo.png';
import { NonstopHomeRedeemCodeSelectedEvent } from '../../models/amplitude/NonstopHomeRedeemCodeSelectedEvent';
import { NonstopHomeRedeemCodeSuccessEvent } from '../../models/amplitude/NonstopHomeRedeemCodeSuccessEvent';
import { PerformTaskResult } from '../../models/tasks/performTaskResult';
import eventEmitter from '../../services/eventEmitter';
import { CloseButton } from './CloseButton';

interface IEnterCodeProps {
    checkCode: (code: string) => Promise<PerformTaskResult>;
    onExit: () => void;
}

interface IEnterCodeState {
    code: string;
    invalidCode: boolean;
    checkingCode: boolean;
    errorMessage: string;
}

export class EnterCode extends Component<IEnterCodeProps, IEnterCodeState> {

    constructor(props: IEnterCodeProps) {
        super(props);
        this.state = {
            checkingCode: false,
            code: '',
            errorMessage: '',
            invalidCode: false,
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    public componentDidMount() {
        eventEmitter.broadcastEvent(AmplitudeEvents.NonstopHomeRedeemCodeSelected, new NonstopHomeRedeemCodeSelectedEvent());
        window.scrollTo(0, 0);
    }

    public render(): ReactNode {
        return (
            <div className='ns-overlay'>
                <div className='ns-container d-flex h-100'>
                   <CloseButton onClick={() => this.props.onExit()} />
                    <div className='text-center activate align-self-center justify-content-center ns-w-100 animated fadeIn'>
                        <div className='ns-row'>
                            <div className='ns-col-8 offset-2 ns-col-md-6 offset-md-3 ns-col-lg-4offset-lg-4'>
                                <img src={nsLogo} className='nonstop-show-logo img-fluid ns-form-logo' alt='logo' />
                            </div>
                        </div>
                        <div className='ns-row'>
                            <div className='ns-col'>
                                <p className='nonstop-preamble-centered'>Enter your code to redeem your points.</p>
                            </div>
                        </div>
                        <form className='ns-redeem-code' onSubmit={this.handleSubmit}>
                            <div className='ns-row'>
                                <div className='ns-col-12 ns-text-center'>
                                    <h1>Enter your code</h1>
                                    <div className={'single-input-group activate-code-input-group ' + (this.state.invalidCode ? 'invalid-code' : '')}>
                                        <input type='text' value={this.state.code} onChange={this.handleChange} disabled={this.state.checkingCode} />
                                        <p className='error-message'>{this.state.errorMessage}</p>
                                    </div>
                                </div>
                            </div>
                            <div className='ns-row'>
                                <div className='ns-col-sm-4 offset-sm-4 button-container'>
                                    <button className={'btn-nonstop w-100 ' + (this.state.checkingCode ? 'btn-disabled' : '')} type='submit'>Enter <i className='fa fa-chevron-right'></i></button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        );
    }

    private handleChange(event: ChangeEvent<HTMLInputElement>) {
        this.setState({
            code: event.target.value,
            errorMessage: '',
            invalidCode: false,
        });
    }

    private async handleSubmit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        if (this.state.checkingCode) {
            return;
        }

        this.setState({ checkingCode: true });
        const checkCodeResult = await this.props.checkCode(this.state.code);
        if (!checkCodeResult || !checkCodeResult.success) {
            this.setState({ errorMessage: checkCodeResult.message, invalidCode: true });
        } else {
            eventEmitter.broadcastEvent(AmplitudeEvents.NonstopHomeRedeemCodeSuccess, new NonstopHomeRedeemCodeSuccessEvent(this.state.code));
            this.props.onExit();
        }
        this.setState({ checkingCode: false });
    }
}