import { ChangeEvent, TargetedEvent, useState } from "preact/compat";
import { createAccountService, loginService } from "../../services";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { authAdded } from "../../features/auth/authSlice/authSlice";
import './index.css';

function Login() {
  const dispatch = useDispatch();
  const { state } = useLocation()
  const [form, setFrom] = useState({
    username: '',
    password: ''
  })

  const [errorMsg, setErrorMsg] = useState([{
    field: '',
    msg: ''
  }])

  const navigation = useNavigate()

  async function handleSignIn(e: TargetedEvent) {
    e.preventDefault();
    try {
      const res = await loginService({ username: form.username, password: form.password })

      if(res.error) {
        if (res.error.response.status == 400) {
          setErrorMsg(res.error.response.data.errors)
          return
        }

        alert(res.error.response.data.message)
        return
      }

      dispatch(authAdded(res.data))

      if (state) {
        navigation(state.from)
        return
      }

      navigation("/")

    } catch (err) {
      console.log(err)
    }
  }

  async function handleSignUp(e: TargetedEvent) {
    e.preventDefault();
    try {
      const res = await createAccountService({
        username: form.username,
        password: form.password
      })

      if (res.error) {
        setErrorMsg(res.error.response.data.errors)
        return;
      }

      dispatch(authAdded(res.data))

      if (state) {
        navigation(state.from)
        return
      }
      navigation("/")

    } catch (err) {
      alert(err)
    }
  }

  function onChangeInput(e: ChangeEvent<HTMLInputElement>) {
    const val = e.target as HTMLInputElement;
    setFrom({ ...form, [val.placeholder]: val.value })
  }

  return (
    <div className={'p-2'}>
      <h1 className={'text-2xl mb-2'}>Sign in</h1>
      <form onSubmit={handleSignIn}>
        <table style={{ borderSpacing: '0 0.5em', borderCollapse: 'separate' }}>
          <tbody>
            <tr>
              <td>username: </td>
              <td><input value={form.username} onChange={onChangeInput} placeholder={'username'} className={'bg-secondary'} /></td>
            </tr>
            <tr>
              <td>password: </td> 
              <td><input value={form.password} onChange={onChangeInput} type={'password'} placeholder={'password'} className={'bg-secondary'} /></td>
            </tr>
          </tbody>
        </table>
        {errorMsg.map(x => (
          <p>{x.msg}</p>
        ))}
        <a className={'block'}>Forgout account ?</a>
        <input type={'submit'} value={'sign in'} className={'p-1 text-sm text-primary mt-4'} style={{ backgroundColor: '#a8adb3', borderRadius: 7 }} />
      </form>
      <h1 className={'text-2xl mt-10'}>Create Account</h1>
      <form onSubmit={handleSignUp} >
        <table style={{ borderSpacing: '0 0.5em', borderCollapse: 'separate' }}>
          <tbody>
            <tr>
              <td>username: </td>
              <td><input value={form.username} onChange={onChangeInput} placeholder={'username'} className={'bg-secondary'} /></td>
            </tr>
            <tr>
              <td>password: </td>
              <td><input value={form.password} onChange={onChangeInput} type={'password'} placeholder={'password'} className={'bg-secondary'} /></td>
            </tr>
          </tbody>
        </table>
        {errorMsg.map(x => (
          <p>{x.msg}</p>
        ))}
        <input type={'submit'} value={'create account'} className={'p-1 text-sm text-primary mt-4'} style={{ backgroundColor: '#a8adb3', borderRadius: 7 }} />
      </form>
    </div>
  )
}

export default Login;