import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import qs from 'qs';
import { Button, Input, Title, SmallText } from '../../../UI';
import postData from '../../function/postData';
import { useAppDispatch } from '../../../../redux/store';
import { fetchToken } from '../../../../redux/login/asyncActions';
import { LoginParams } from '../../../../redux/login/types';
import { selectTokenData } from '../../../../redux/login/selectors';
//{setToken, updateData}

export const Entrance: React.FC = () => {
    const [_data, setData] = useState({login:'',password:''});
    const dispatch = useAppDispatch();
    const { token, status_token } = useSelector(selectTokenData);
    const [information, setInformation] = useState('');

    const getToken = async () => {
        console.log(_data);
        dispatch(
          fetchToken({
            login: String(_data.login),
            password:String(_data.password),
          }),
        );
        console.log(status_token);
      };
      React.useEffect(() => {
        const params = qs.parse(window.location.search.substring(1)) as unknown as LoginParams;
        console.log(params);
    }, []);

    const onChange = (name: string, value:string) => {
        setData({ ..._data, [name]: value});
    };

    const reset = (name: string, value:string) => {
        setData({ ..._data, [name]: value});
    };

    const handleEntrance = () => {
        console.log(_data);
        /*postData('/api/login', { _data })
            .then((data) => {
                console.log(data);
                data.token ?
                setToken(data) :
                setInformation(data.error);
        }); */
     }
    return(
        <>
            <Title> Вход в систему </Title>
            <Input label={'Логин'} name={'login'} type={'text'} onChange={onChange} value={_data.login}/>
            <Input label={'Пароль'} name={'password'} type={'password'} onChange={onChange} value={_data.password}/>
            <Button onClick={getToken} align={''} styles={'yellow'}>Войти</Button>
            <Button onClick={handleEntrance} align={''} styles={'yellow'}>Забыл/Сбросить пароль</Button>
            <SmallText>{information}</SmallText>
        </>
    )
}


