import React, { useState } from 'react';
import PropTypes from 'prop-types';
import Button from '../../component/Button';
import Input from '../../component/Input';
import Title from '../../component/Title';
import Label from '../../component/Label';
import postData from '../../function/postData';

const NewPassword = (props) => {
    const [_data, setData] = useState({email: props.email, password:'', passwordRepeat:''});
    const [information, setInformation] = useState('');
    const updateData = e => {
        setData({ ..._data, [e.target.name]: e.target.value});
      }
    const handleEntrance = () => {
        console.log(_data);
        if (_data.password === _data.passwordRepeat) {
            postData('/api/newpassword', {_data})
                .then((data) => {
                    console.log(data[0]);
                    data.token ? props.setToken(data) : setInformation(data.error);
                   // setToken(data[0]);
            });
        } else {setInformation('Пароли не совпадают');}
     }
    return(
        <>
            <Title> Введите новый пароль </Title>
            <Input label={'Новый пароль'} type={'password'} name={'password'} onChange={updateData} value={_data.password}/>
            <Input label={'Повтор нового пароля'} type={'password'} name={'passwordRepeat'} onChange={updateData} value={_data.passwordRepeat}/>
            <Button name={'Entrance'} onClick={handleEntrance}>Сохранить пароль</Button>
            <Label>{information}</Label>
        </>
    )
}

NewPassword.propTypes = {
    setToken: PropTypes.func.isRequired
  }

export default NewPassword;