import {Link, Switch} from "react-router-dom";
import {connect} from "react-redux";
import {actionAuthLogout, actionPromise} from "../../reducers";
import {CLoginForm} from "./login";
import {CRegForm} from "./registration";
import {useState} from "react";
import {CAvatar,CAvatarDropZone} from "./avatar";
import {Logo} from "./logo";
import {history} from "../../App";
import {gql} from "../../actions";
import {takeEvery, select, call} from "redux-saga/effects";
import {promiseWorker} from "../../reducers/promiseReducer";
import {CTrackSearch} from "../tools/search";
import {CProtectedRoute} from "../../reducers/routeReducer";


export const actionSetUserPassword = (password) =>
    ({type:'SET_USER_PASSWORD', password})

export function* setUserPasswordWorker (action) {
        let {password} = action
        let {auth} = yield select()
        let userId = auth.payload?.sub?.id
        console.log(userId, password)
        // yield put (actionAuthLogout())
        yield call(promiseWorker,actionPromise('register', gql(`mutation reg($user:UserInput) {
         UserUpsert(user:$user) {
         _id 
         }
      }`, {user: {userId, password}})))
        // yield put (actionFullLogin)
}


export function* setUserPasswordWatcher() {
    yield takeEvery ('SET_USER_PASSWORD',setUserPasswordWorker)
}

const ChangePasswordForm = ({onChangePassword}) => {
    const [p, setP] = useState ('')
    return (
        <div>
            <input className='change-password-input' type='password' placeholder='Введите пароль' onChange={e => setP(e.target.value)}></input>
            <button className='dropdown-button' onClick={() => {onChangePassword(p); history.push('/')}}>Сменить пароль</button>
        </div>
    )
}

export const CChangePasswordForm = connect(null,{onChangePassword:actionSetUserPassword})(ChangePasswordForm)


export const Header = () =>
    <header className="Header">
        <Logo />
        <Link to={`/music`}><h3>Все песни</h3></Link>
        <Link to={`/myMusic`}> <h3>Моя музыка</h3></Link>
        <h3><CTrackSearch /></h3>


        <Switch>
            <CProtectedRoute roles={["anon", "user"]} path="/login" component={CLoginForm}/>
            <CProtectedRoute roles={["anon", "user"]} path="/registration" component={CRegForm}/>
            <CProtectedRoute roles={["anon", "user"]} path='*' component={CLoginButtons} exact/>
        </Switch>
    </header>



const LoginButtons = ({onLogout, history, token}) => {
    return (
        <>
            {!token ?
                ( <div className='LoginButtons'>
                    <Link to='/login'><button onClick={() => history.push('/')}>Вход</button></Link>
                    <Link to='/registration'><button>Регистрация</button></Link></div>) :
                (<div className="btn-group">
                        <button type="button" className="btn btn-secondary dropdown-toggle" data-toggle="dropdown"
                                aria-haspopup="true" aria-expanded="false">
                            <CAvatar/>
                        </button>
                        <div className="dropdown-menu dropdown-menu-right">
                            <h2>{JSON.parse(atob(token.split(".")[1])).sub.login}</h2>
                            <CAvatarDropZone />
                            <CChangePasswordForm/>
                            <button className='dropdown-button' onClick={() => {onLogout(); history.push('/')}}>Выйти</button>
                        </div>
                    </div>

                )
            }
        </>
    )
}
export const CLoginButtons = connect(state => ({token: state.auth.token}), {onLogout: actionAuthLogout})(LoginButtons)