import * as React from "react";
import { isEqual } from "lodash";

export interface DataItem {
    id: string;
    name: string;
}

export const sumElements = (arr: number[]) =>
    arr.reduce((prev: number, curr: number) => prev + curr, 0);

export namespace TestComponent {
    export interface Props {
        pwChange: (value: string) => void;
        pwPress: (value: string) => void;
        unChange: (value: string) => void;
        data: DataItem[];
    }
    export interface State {
        success: boolean;
        username: string;
        password: string;
        data: DataItem[];
    }
}

class TestComponent extends React.Component<
    TestComponent.Props,
    TestComponent.State
> {
    state = {
        success: false,
        username: "",
        password: "",
        data: [],
    };

    sumElements;

    componentWillReceiveProps(nextProps: TestComponent.Props) {
        if (!isEqual(this.props.data, nextProps.data)) {
            this.setState({ data: nextProps.data });
        }
    }

    handleSubmit = (e: any): void => {
        e.preventDefault();
        setTimeout(() => {
            this.setState({ success: true });
        }, 500);
    };

    usernameChange = (e): void => {
        const {
            target: { value },
        } = e;
        this.props.unChange(value);
    };

    passwordChange = (e): void => {
        const {
            target: { value },
        } = e;
        this.props.pwChange(value);
    };

    passwordPress = (e): void => {
        const {
            target: { key },
        } = e;
        this.props.pwPress(key);
    };

    render() {
        return (
            <>
                {this.state.data.map((item: DataItem) => (
                    <span key={item.id}>{item.name}</span>
                ))}

                <form onSubmit={this.handleSubmit}>
                    {this.state.success && (
                        <div data-testid="submit-success">Success!</div>
                    )}
                    <label htmlFor="username-field">Username</label>
                    <input onChange={this.usernameChange} id="username-field" />
                    <label htmlFor="password-field">Password</label>
                    <input
                        onChange={this.passwordChange}
                        onKeyDown={this.passwordPress}
                        id="password-field"
                    />
                    <button type="submit">Submit</button>
                </form>
            </>
        );
    }
}

export default TestComponent;
