import {CUsersList, SearchUserInput, CUpdateAdminForm} from "./index";
import {gql, urlUpload, actionPromise, actionGoodCard, getGoods,
    actionUserFindOne, updateImgAction, actionAuthLogin, actionAuthLogout,
    actionUserUpdate, actionOrdersFind, getData, actionLogin } from "../reducers";
import {createStore, combineReducers, applyMiddleware, bindActionCreators} from 'redux';
import { connect } from "react-redux";
import { useEffect, useState, useRef } from "react";

import {BrowserRouter as Router, Route, Link, Switch, Redirect, useHistory} from 'react-router-dom';
import { NewAuth } from "../reducers/actionAuthLog";


const YourProfile = ({state, orders, loginStatus = {}, updateStatus, updatedUser = {}, newImg, token, onLogin, onLogout, updateImg, 
                        updateUser, isUserAdmin = {}, status, data = {}, getData, 
                        match:{params:{_id}}, isAdmin = [], isOwner = {}, newPicture = "clear"}) => {

    const history = useHistory();

    const [nick, changeNick] = useState(null);
    const [newLogin, changeLogin] = useState(null);
    const [nowPassword, superPassword] = useState(null);
    const [password, changePassword] = useState(null);
    const [password2, changePassword2] = useState(null);
    const [isUpdateImg, changeImg] = useState(false);
    const [falseTrying, OneRty] = useState(false)
    // const [isUpdatePage, changePage] = useState(false);
    // const [newImage, getImage] = useState({});

     useEffect(() =>   {
       if(history.location.pathname.includes(`/profile/`)) {
        getData(`${isOwner.id}`);
        orders(`${isOwner.id}`) ;
       }
       else {
        getData(`${_id}`);
        if(isAdmin) {
        orders(`${_id}`) ;
        }
       }
    },[history.location.pathname])

     useEffect( 
       async() => {

       if(updateStatus == "RESOLVED" && updatedUser && updatedUser.data && updatedUser.data.UserUpsert) {
                           
          if(!isAdmin || (isAdmin && isOwner.id == data._id)){

              await onLogin(newLogin|| data.login, password || nowPassword);

           } 
          // window.location.reload()

      }
    }, [updateStatus])
     
     

     
     const date = new Date(data ? +data.createdAt : 0);
     const [showUpdate, onShow] = useState(false);
     const [searchInput, changeValue] = useState("Пошук");
     

       console.log(state);
    // //  console.log(data);
     

        return (
          
          <>
          { (status == "RESOLVED" && data) &&
            <>
            <div className = "userSearch">
                <input type = "text" placeholder = "Пошук юзера" onChange = {e => changeValue(e.target.value)} onKeyDown = {(e) => e.keyCode == 13 && history.push(`/searchUser/${searchInput}`)}/>
                <Link to = {"/searchUser/" + searchInput}>
                    <button>Пошук</button>
                </Link>
            </div>

                <div className = "profilePage">
                    
                    {(isUserAdmin )&& 
                    <div className = "adminSmile">
                    <svg  xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" className="bi bi-emoji-sunglasses-fill" viewBox="0 0 16 16">
                    <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zM2.31 5.243A1 1 0 0 1 3.28 4H6a1 1 0 0 1 1 1v.116A4.22 4.22 0 0 1 8 5c.35 0 .69.04 1 .116V5a1 1 0 0 1 1-1h2.72a1 1 0 0 1 .97 1.243l-.311 1.242A2 2 0 0 1 11.439 8H11a2 2 0 0 1-1.994-1.839A2.99 2.99 0 0 0 8 6c-.393 0-.74.064-1.006.161A2 2 0 0 1 5 8h-.438a2 2 0 0 1-1.94-1.515L2.31 5.243zM4.969 9.75A3.498 3.498 0 0 0 8 11.5a3.498 3.498 0 0 0 3.032-1.75.5.5 0 1 1 .866.5A4.498 4.498 0 0 1 8 12.5a4.498 4.498 0 0 1-3.898-2.25.5.5 0 0 1 .866-.5z"/>
                    </svg>
                    <span>admin</span>
                    </div>
                    }
                    
                    { (isOwner.id == data._id) ? <h2>Привіт, {data.nick || "людино"}!</h2> : <h2>{data.nick || data.login}</h2>}

                    <img src={data.avatar ? `${urlUpload}/${data.avatar.url}`: 'https://pngicon.ru/file/uploads/picca-1.png'} />
                    <span>
                        Сторінку створено {`${date.getDate()}. ${date.getMonth() + 1}. ${date.getFullYear()} о ${date.getHours()}: ${date.getMinutes()}: ${date.getSeconds()}  `}
                    </span>
                    {( (isOwner.id == data._id) || (isAdmin && !isUserAdmin))  &&
                    <span>
                        <button  onClick = {() => onShow(!showUpdate)}>Редагувати</button>
                    </span>
                    }
                    {showUpdate && 
                    <div className = "updateWrapper">
                    <h4>Редагування</h4>
                    
                    {((loginStatus.status && loginStatus.status == "RESOLVED" && !loginStatus.payload.data.login) 
                    ||(updatedUser && updatedUser.errors && updatedUser.errors.length > 0))
                     && <p>Цей логін вже зайнято, або невірний пароль</p>}
                    

                    {(!isAdmin  || (isAdmin && isOwner.id == data._id))&&
                    <input type = "password" onChange = {(e) => superPassword(e.target.value)} placeholder = "Пароль"/>}
                    
                    <input onChange = {(e) => changeNick(e.target.value)} placeholder = "Новий нікнейм"/>
                    <input onChange = {(e) => changeLogin(e.target.value)} placeholder = "Новий логін"/>
                    <input type = "password" onChange = {(e) => changePassword(e.target.value)} placeholder = "Новий пароль"/>
                    <input type = "password" onChange = {(e) => changePassword2(e.target.value)} placeholder = "Повторіть пароль"/>
                    <input type="file"  name="photo" id='photo' 
                      onChange={(ev) => {
                        updateImg(ev.target.files[0])
              
                        changeImg(true);
                      }
                        }/>
                    <button disabled = {(newPicture == "PENDING") ||
                       ( !isAdmin && !nowPassword) || 
                        ((isAdmin && isOwner.id == data._id) && !nowPassword )}  
                         onClick = {
                        async () => {

                          if(!isAdmin || (isAdmin && isOwner.id == data._id)){

                            await onLogin( data.login, nowPassword);

                           }
                            let newUser = {};
                            newUser._id = data._id;
                            if(nick){
                              newUser.nick = nick;
                            }
                            if (newLogin){
                              newUser.login = newLogin;
                            }
                            if (password && password == password2) {
                              newUser.password = password;
                            } else if (password !== password2) {
                              history.push("/loginError");
                              return
                            }
                            if(isUpdateImg) {

                              newUser.avatar = {};
                              newUser.avatar._id = newImg._id;
                              newUser.avatar.url = newImg._url;
                            }
                              updateUser(newUser);



                    }}>Зберегти</button>
                  </div>

                        
                    }
                    

                    
                </div>
            </>
          }

          </>
        )
       
}

const mapStateToProps = state => ({
     state: state,

     status: state.promiseRed && state.promiseRed.user &&
     state.promiseRed.user.payload && state.promiseRed.user &&
     state.promiseRed.user.status,

     data: state.promiseRed && state.promiseRed.user &&
     state.promiseRed.user.payload && state.promiseRed.user.payload.data &&
     state.promiseRed.user.payload.data.UserFindOne,

     newPicture: state.promiseRed && state.promiseRed.photo &&
     state.promiseRed.photo.status,
     
     token: state.auth && state.auth.token,

     updatedUser: state.promiseRed && state.promiseRed.newUser &&
     state.promiseRed.newUser.payload && state.promiseRed.newUser.payload.data &&
     state.promiseRed.newUser.payload,

     loginStatus: state.promiseRed && state.promiseRed.login,

     updateStatus: state.promiseRed && state.promiseRed.newUser &&
     state.promiseRed.newUser.status,

     isUserAdmin: state.promiseRed && state.promiseRed.user &&
     state.promiseRed.user.payload && state.promiseRed.user.payload.data &&
     state.promiseRed.user.payload.data.UserFindOne && 
     state.promiseRed.user.payload.data.UserFindOne.acl &&
     state.promiseRed.user.payload.data.UserFindOne.acl.indexOf("admin") > -1,

     isOwner: state.auth && state.auth.payload && state.auth.payload.sub &&
     state.auth.payload.sub,

     newImg: state.promiseRed && state.promiseRed.photo &&
     state.promiseRed.photo.payload && state.promiseRed.photo.payload,

     isAdmin: state.auth && state.auth.payload && state.auth.payload.sub &&
     state.auth.payload.sub.acl && state.auth.payload.sub.acl.indexOf("admin") > -1,

     
  });


  
  const mapDispatchToProps = dispatch => bindActionCreators({
    getData: actionUserFindOne,
    updateImg: updateImgAction,
    updateUser: actionUserUpdate,
    onLogout: actionAuthLogout,
    onLogin: actionLogin,
    orders: actionOrdersFind
  }, dispatch);

const CYourProfile = connect(mapStateToProps, mapDispatchToProps)
(YourProfile)
export default CYourProfile;

