import './App.css';
import { BrowserRouter, Route, Switch ,useLocation } from 'react-router-dom';
import { useState , useEffect } from 'react';
import {  logout } from './reducers/userR';
import {useSelector , useDispatch} from 'react-redux'
import {registration,login,auth } from "./actions/user"
import {saveProject , reSaveProject, showProject,showAllProject,userProject,deleteProject} from "./actions/project"


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 =()=>{
  let user = useSelector(state => state.user.currentUser.id)
  let email = useSelector(state => state.user.currentUser.email)
  let codeHTML ,codeCSS , codeJS ,title 
  const isAuth = useSelector(state => state.user.isAuth)

  const htmlCodeGenerator=(codeHtml)=>{
    const htmlOutput = document.getElementById("htmlOutput")
    htmlOutput.innerHTML=codeHtml
    codeHTML=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>`
    codeCSS=trueCSS
  }

  const runJsCode =()=>{
    try{
      eval(codeJS)
    }catch(e){
      console.log(e)
    }
  }

  return(
    <div>
      <fieldset className="title">
        <legend>Title</legend>
        <textarea  onChange={txt => title=txt.target.value} className="nameProj" name="title"></textarea>
        { isAuth&&<button className='saveProject' type='button'  onClick={()=> saveProject(title,codeHTML,codeCSS,codeJS,user,email)}>Save new project</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)=>{codeJS=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 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=()=>{
  const email = useSelector(state => state.user.currentUser.email)
  showProject(email)
  return(
    <fieldset className="project">
        <legend>My Project</legend>
        <ul className="myProject"id="tableUserProj">
        </ul>
    </fieldset>
  )
}
const Project=()=>{
  showAllProject()
  return(
    <fieldset className="project">
        <legend>Project</legend>
        <ul className="worldProject" id="worldProject" >
          <li className="creatorProject" ><a href="/">++++++++++CREATE+A+NEW+PROJECT++++++++++</a></li>
        </ul>
    </fieldset>
  )
}
const ProjectID =()=>{
  let userActiv = useSelector(state => state.user.currentUser.id)
  let emailActiv = useSelector(state => state.user.currentUser.email)
  let idProject = useLocation();
  let dataProj 

  const [codeHTML,setCodeHTML]=useState('')
  const [codeCSS,setCodeCSS]=useState('')
  const [codeJS,setCodeJS]=useState('')
  const [title,setTitle]=useState('')
  const [user,setUser]=useState('')
  

  const htmlCodeGenerator=(e)=>{
    const htmlOutput = document.getElementById("htmlOutput")
    setCodeHTML(e)
    htmlOutput.innerHTML=codeHTML
    console.log(codeHTML)
  }

  const cssCodeGenerator=(e)=>{
    const cssOutput = document.getElementById("cssOutput")
    setCodeCSS(e)
    cssOutput.innerHTML=`<style type="text/css" id="styl">${e}</style>`
  }

  const runJsCode =()=>{
    try{
      eval(codeJS)
    }catch(e){
      console.log(e)
    }
  }
   return(
    <div>
      <fieldset className="title">
        <legend >Title</legend>
        <textarea  onChange={(e) => setTitle(e)} value={title} className="nameProj" id="titlePPRJ" name="title"></textarea>
        <button className='saveProject' type='button' onClick={()=> userProject(idProject).then(res=>{dataProj=res}).then(() => setCodeHTML(dataProj[0])).then(() => setCodeCSS(dataProj[1])).then(() => setCodeJS(dataProj[2])).then(() => setTitle(dataProj[3])).then(() => setUser(dataProj[4]))}>Show project</button> 
        <button className='saveProject' type='button'  onClick={()=> saveProject(title,codeHTML,codeCSS,codeJS,userActiv,emailActiv)}>Save new project</button>
        {user==userActiv && <button className='saveProject' type='button'  onClick={()=> reSaveProject(idProject,title,codeHTML,codeCSS,codeJS)}>Save changes</button>}
        {user==userActiv && <button className='saveProject' type='button'  onClick={()=> deleteProject(idProject)}>Deleted project</button>}
      </fieldset>
       <form className="ide">
        <fieldset className="dev" >
          <legend>codeHTML</legend>
          <AceEditor className="windDev" onChange={(e) => htmlCodeGenerator(e)} value={codeHTML}  placeholder="your html code could be here ..." mode="html" 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%"}}></AceEditor>,
        </fieldset>
        <fieldset className="dev">
          <legend>codeCSS</legend>
          <AceEditor className="windDev"  value={codeCSS} onChange={(e) =>cssCodeGenerator(e)} id="coderCSS" 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" value={codeJS} onChange={(cods)=>{setCodeJS(cods)}} id="coderJS" placeholder="your js code could be here ..." mode="javascript" theme="terminal" name="blah3"  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 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="/MyProject" 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/>
            <Route path="/id/:id" component={ProjectID}/>
          </Switch>
        </BrowserRouter>)
}

export default App;
