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'
import {registration,login,auth } from "./actions/user"

import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-html";
import "ace-builds/src-noconflict/mode-css";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-terminal";
import "ace-builds/src-noconflict/ext-language_tools"

const Sandbox =()=>{
  const {request}=useHttp()
  const dispatch = useDispatch()
  let user 

  let title
  let codeHTML 
  let codeCSS 
  let codeJS 

  const  saveProject = async () => {
    try {
      const data = await request('/api/authorization/registration', 'POST', {user,title,codeHTML,codeCSS,codeJS})
    } catch (e) {console.log(e)}
  }

  const htmlCodeGenerator=(codeHTML)=>{
    const htmlOutput = document.getElementById("htmlOutput")
    htmlOutput.innerHTML=codeHTML
  }

  const cssCodeGenerator=(codeCSS)=>{
    const cssOutput = document.getElementById("cssOutput")
    var trueCSS = codeCSS.replace(/body/gi, '.body')
    cssOutput.innerHTML=`<style type="text/css" id="styl">${trueCSS}</style>`
  }

  let jsnov
  const runJsCode =()=>{
    eval(jsnov)
  }

  return(
    <div>
      <fieldset className="title">
        <legend>Title</legend>
        <textarea className="nameProj" name="title">{title}</textarea>
        <button className='saveProject' type='button' onClick={saveProject} >save</button>
      </fieldset>
       <form className="ide">
        <fieldset className="dev">
          <legend>codeHTML</legend>
          <AceEditor className="windDev" onChange={htmlCodeGenerator} id="coderHTML" placeholder="your html code could be here ..." mode="html" value={codeHTML} theme="terminal" name="coderHTML"  fontSize={14} showPrintMargin={true} showGutter={true} highlightActiveLine={true} setOptions={{ enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: true, showLineNumbers: true,tabSize: 2,}} style={{height:"380px",width:"100%"}}/>,
        </fieldset>
        <fieldset className="dev">
          <legend>codeCSS</legend>
          <AceEditor className="windDev" onChange={cssCodeGenerator} placeholder="your css code could be here ..." mode="css" value={codeCSS} theme="terminal" name="blah2"  fontSize={14} showPrintMargin={true} showGutter={true} highlightActiveLine={true} setOptions={{ enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: true, showLineNumbers: true,tabSize: 2,}} style={{height:"380px",width:"100%"}}/>,
        </fieldset><fieldset className="dev">
          <legend>codeJS</legend>
          <AceEditor className="windDev" onChange={(cods)=>{jsnov=cods}} placeholder="your js code could be here ..." mode="javascript" theme="terminal" name="blah2"  fontSize={14} showPrintMargin={true} showGutter={true} highlightActiveLine={true} value={codeJS} setOptions={{ enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: true, showLineNumbers: true,tabSize: 2,}} style={{height:"380px",width:"100%"}}/>,
          <a className="legend3" onClick={runJsCode}>run script</a>
        </fieldset>    
      </form>
      <fieldset className="body" style={{backgroundColor:"#2f0000"} }>
      <legend>outPut</legend>
        <div  id="htmlOutput"/>
        <div  id="cssOutput"/>
      </fieldset>
    </div>
  )
}

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;
    }
  }


  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(login(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 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={()=> registration(email,password)}>Registration</button>
        {(emailWrong&&emailError)&& <p style={{color:'orange'}}>{emailError}</p>}
        {(passwordWrong&&passwordError) && <p style={{color:'orange'}}>{passwordError}</p>}
      </form>
      <a href="/login" className="legend2">Login</a>
    </fieldset>
  )
}


const MyProject=()=>{
  return(
    <fieldset className="project">
        <legend>My Project</legend>
        <ul className="myProject">
          <li className="creatorProject"><a href="/">++++++++++CREATE+A+NEW+PROJECT++++++++++</a></li>
        </ul>
    </fieldset>
  )
}
const Project=()=>{
  return(
    <fieldset className="project">
        <legend>Project</legend>
        <ul className="worldProject">
          <li className="creatorProject"><a href="/">++++++++++CREATE+A+NEW+PROJECT++++++++++</a></li>
        </ul>
    </fieldset>
  )
}


const App =()=>{
  const isAuth = useSelector(state => state.user.isAuth)
  const dispatch = useDispatch()

  useEffect(() => {
      dispatch(auth())
  }, [])
  return(
        <BrowserRouter>
          <div className="navBar">
            <h1 className="logo"><a href="/">SandBox</a></h1>
            <a href="/" className="links">Sandbox</a>
            {isAuth && <a href="/my_project" className="links">My project</a>}
            <a href="/Project" className="links">Project</a>
            {isAuth && <a onClick={()=>dispatch(logout())} className="links" style={{cursor:"pointer"}}>Exit</a>}
            {!isAuth && <a href="/login" className="links" style={{cursor:"pointer"}}>Login</a>}
          </div>
          {!isAuth &&
          <Switch>
            <Route path="/login" component={AuthorizationLogin}/>
            <Route path="/registration" component={AuthorizationRegistration}/>
          </Switch>
          }
          <Switch>
            <Route path="/" component={Sandbox} exact/>
            <Route path="/MyProject" component={MyProject} exact/>
            <Route path="/Project" component={Project} exact/>
          </Switch>
        </BrowserRouter>)
}

export default App;
