import './App.css';
import { BrowserRouter, Route, Switch} from 'react-router-dom';
import { useState , useEffect , dispatch ,response} from 'react';
import { useHttp  } from './hooks/httpReqest'
import { setUser , logout } from './reducers/userR';
import {useSelector , useDispatch} from 'react-redux'


const AuthorizationLogin = () =>{
  const [email,setEmail]=useState('')
  const [password,setPassword]=useState('')
  const [emailWrong, setEmailWrong]=useState(false)
  const [passwordWrong, setPasswordWrong]=useState(false)
  const [emailError,setEmailError]=useState('email empty')
  const [passwordError,setPasswordError]=useState('password empty')
  const {request}=useHttp()
  const dispatch = useDispatch()
  const emailHandler = (e)=>{
    setEmail(e.target.value)
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if(!re.test(String(e.target.value).toLowerCase())){
      setEmailError('invalid login')
    }else{
      setEmailError("")
    }
  }
  const passwordHandler = (e)=>{
    setPassword(e.target.value)
    if(e.target.value.length<=3){
      setPasswordError('password must be longer than 6 characters')
    }else{
      setPasswordError('')
    }
  }
  const outInput = (e) =>{
    switch(e.target.name){
      case 'email':
        setEmailWrong(true)
      break;
      case 'password' : 
        setPasswordWrong(true)
      break;
    }
  }
  const loginHandler = (email,password)=>{
    return async dispatch =>{
      try{
        const response = await request('/api/authorization/login', 'POST', {email,password})
        dispatch(setUser(response.user))
        localStorage.setItem('token',response.token)
        console.log(response.user)
      }catch (e){
        console.log(e.message)
      }
    }
  }
  return(
    <fieldset className="logForm">
      <legend className="lr_title">Login</legend>
      <form className="login">
        <fieldset>
          <legend>Email</legend>
          <input onChange={e => emailHandler(e)} value={email} onBlur={e=>outInput(e)} name='email' className='email' type="text" placeholder='Enter you email...'/>
        </fieldset>
        <fieldset>
          <legend>Password</legend>
          <input onChange={e => passwordHandler(e)}value={password} onBlur={e=>outInput(e)} name='password' className='password'  type="password" placeholder='Enter you password...'/>
        </fieldset>
        <button className='submitLR' type='button' onClick={()=>dispatch(loginHandler(email,password))}>Login</button>
        {(emailWrong&&emailError)&& <p style={{color:'orange'}}>{emailError}</p>}
        {(passwordWrong&&passwordError) && <p style={{color:'orange'}}>{passwordError}</p>}
      </form>
      <a href="/registration" className="legend2">Registration</a>
    </fieldset>
  )
}
const AuthorizationRegistration = () =>{
  const [email,setEmail]=useState('')
  const [password,setPassword]=useState('')
  const [emailWrong, setEmailWrong]=useState(false)
  const [passwordWrong, setPasswordWrong]=useState(false)
  const [emailError,setEmailError]=useState('email empty')
  const [passwordError,setPasswordError]=useState('password empty')
  const {request}=useHttp()
  const registrationHandler = async () => {
    try {
      const data = await request('/api/authorization/registration', 'POST', {email,password})
    } catch (e) {setEmailError(e.message)}
  }

  const emailHandler = (e)=>{
    setEmail(e.target.value)
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if(!re.test(String(e.target.value).toLowerCase())){
      setEmailError('invalid login')
    }else{
      setEmailError("")
    }
  }
  const passwordHandler = (e)=>{
    setPassword(e.target.value)
    if(e.target.value.length<=3){
      setPasswordError('password must be longer than 6 characters')
    }else{
      setPasswordError('')
    }
  }
  const outInput = (e) =>{
    switch(e.target.name){
      case 'email':
        setEmailWrong(true)
      break;
      case 'password' : 
        setPasswordWrong(true)
      break;
    }
  }
  return(
    <fieldset className="logForm">
      <legend className="lr_title">Registration</legend>
      <form className="login">
        <fieldset>
          <legend>Email</legend>
          <input onChange={e => emailHandler(e)} value={email} onBlur={e=>outInput(e)} name='email' className='email' type="text" placeholder='Enter you email...'/>
        </fieldset>
        <fieldset>
          <legend>Password</legend>
          <input onChange={e => passwordHandler(e)}value={password} onBlur={e=>outInput(e)} name='password' className='password'  type="password" placeholder='Enter you password...'/>
        </fieldset>
        <button className='submitLR' type='button' onClick={registrationHandler}>Registration</button>
        {(emailWrong&&emailError)&& <p style={{color:'orange'}}>{emailError}</p>}
        {(passwordWrong&&passwordError) && <p style={{color:'orange'}}>{passwordError}</p>}
      </form>
      <a href="/" className="legend2">Login</a>
    </fieldset>
  )
}



const App =()=>{
  const isAuthorization = useSelector(state => state.user.isAuth)
  const dispatch =useDispatch()
  const {request}=useHttp()

  const authorization =() =>{
    return async dispatch =>{
      try{
        const response = await request('/api/authorization', 'GET',  {headers:{Authorization:`Bearer ${localStorage.getItem('token')}`}})
        dispatch(setUser(response.user))
        localStorage.setItem('token', response.token)
      }catch(e){
        console.log(e)
        localStorage.removeItem('token')
      }
    }
  }
  useEffect(()=>{
    dispatch(authorization())
  },[])




  return(
        <BrowserRouter>
          <div className="navBar">
            <h1 className="logo"><a href="/">SandBox</a></h1>
            <a href="/Project" className="links">Project</a>
            <a href="/my_project" className="links">My project</a>
            <a href="/sandbox" className="links">Sandbox</a>
            {isAuthorization && <a onClick={()=>dispatch(logout())} className="links" style={{cursor:"pointer"}}>Exit</a>}
          </div>
          {!isAuthorization &&
          <Switch>
            <Route path="/" component={AuthorizationLogin} exact/>
            <Route path="/registration" component={AuthorizationRegistration}/>
          </Switch>
          }
        </BrowserRouter>)
}

export default App;
