import './Login.sass'
import { Logo, Link, Page, Row, Padding, Box, Radio, Combobox, Input, Button, Modal, Column } from '../../components'
import { IoChevronBack } from 'solid-icons/io'
import { createSignal, Show, createEffect } from 'solid-js'
import { ofetch } from 'ofetch'
import { SHA1, SHA3 } from 'crypto-js'
import { useNavigate } from '@solidjs/router'
import { checkConnection } from '../../utils/functions'
import { _employeeId, _employeeName } from '../../stores/employee'

export default () => {
  const API = import.meta.env.VITE_BACKEND
  const APPROVERNAME = import.meta.env.VITE_HEAD
  const navigate = useNavigate()
  const assessors = JSON.parse(sessionStorage.getItem('registered')!)
  const roles = ['Assessor', 'Approver']

  const [role, setRole] = createSignal('Assessor')
  const [name, setName] = createSignal('')
  const [password, setPassword] = createSignal('')
  const [loggedin, setLoggedin] = createSignal(0)
  const [errorMessage, setErrorMessage] = createSignal('')
  const [connected, setConnected] = createSignal(true)

  const login = async () => {
    setConnected(await checkConnection())
    if (connected() === false) {
      setErrorMessage('No Connection on Server')
      return
    }

    const employeeid = await ofetch(API + 'get-employeeid/' + name(), { parseResponse: JSON.parse })
    const dbpassword = await ofetch(API + 'get-password/' + employeeid.result, { parseResponse: JSON.parse })
    const hashPassword = await securePassword()

    if (dbpassword.result === '0') {
      setErrorMessage('Not yet registered. Please proceed to Registration.')
    } else {
      setErrorMessage('Invalid Password, Try again.')
    }

    if (dbpassword.result === hashPassword) {
      _employeeId.set(employeeid.result)
      _employeeName.set(name())
      saveEmployee()
      setLoggedin(2)
    } else {
      setLoggedin(1)
    }
  }

  const securePassword = async () => {
    const firstHashing = SHA1(password())
    const secondHashing = SHA3(firstHashing)
    const thirdHashing = SHA1(secondHashing)

    return thirdHashing.toString()
  }

  const gotoMain = () => {
    navigate('/main')
  }

  const gotoAssessor = () => {
    navigate('/assessor')
  }

  const navigateToRolePage = () => {
    if (role() === 'Assessor') gotoAssessor()
    else gotoMain()
  }

  const saveEmployee = () => {
    sessionStorage.setItem('id', _employeeId.get().toString())
    sessionStorage.setItem('name', _employeeName.get())
  }

  createEffect(() => {
    if (role() === 'Approver') setName(APPROVERNAME)
    else if (role() !== 'Approver' && name() === APPROVERNAME) setName('')
  })

  return (
    <>
      <Page alignment="column">
        <Padding left={4.75} right={4.75} top={0} bottom={0}>
          <Row content="split">
            <Link to="/">
              <Row content="left" gap={2}>
                <Logo size={200} />
                <h1>OCBO e-Sign</h1>
              </Row>
            </Link>

            <Link to="/">
              <Row content="right">
                <IoChevronBack size={45} />
                <span class="back-button-text">Back</span>
              </Row>
            </Link>
          </Row>

          <Padding top={2} left={0} right={0} bottom={0}>
            <Row>
              <Box curved thickness={2} padding="2.25rem" color="#253849be" background="#04040660">
                {/* <section class="box"> */}
                <Row>
                  <span class="box-title">Login</span>
                </Row>

                <Padding top={2} left={2} right={2} bottom={0}>
                  <Row>
                    <Radio data={roles} value={role()} onChange={setRole} gap={10} />
                  </Row>
                </Padding>
                <h4>Name</h4>
                <Show when={role() !== 'Approver'}>
                  <Combobox options={assessors} placeholder="Select your name" value={name()} onChange={setName} />
                </Show>
                <Show when={role() === 'Approver'}>
                  <span class="approver-name">{APPROVERNAME}</span>
                </Show>
                <h4>Password</h4>
                <Input
                  value={password()}
                  onChange={setPassword}
                  onKeyDown={(event: KeyboardEvent) => {
                    if (event.key === 'Enter') login()
                  }}
                />

                <Padding top={2} left={0} right={0} bottom={0}>
                  <Show when={password() && name()}>
                    <Row>
                      <Button edges="curved" design="bo-primary" label="Login" wide onClick={login}></Button>
                    </Row>
                  </Show>

                  <Show when={!password() && name()}>
                    <Row>
                      <span class="required">Required password</span>
                    </Row>
                  </Show>

                  <Show when={!password() && !name()}>
                    <Row>
                      <span class="required">Required name and password</span>
                    </Row>
                  </Show>

                  <Show when={password() && !name()}>
                    <Row>
                      <span class="required">Required name</span>
                    </Row>
                  </Show>
                </Padding>
                {/* </section> */}
              </Box>
            </Row>
          </Padding>
        </Padding>
      </Page>

      <div onClick={navigateToRolePage}>
        <Modal trigger={loggedin() === 2} background="#123220ff" color="#cdfbe1f0" opacity={0.8}>
          <Padding top={1} bottom={1} left={4} right={4}>
            <Column>
              <Row>
                <Box curved thickness={3} color="#cdfbe1f0" padding="1rem">
                  <h2>Login Successful</h2>
                </Box>
              </Row>

              <Row>
                <span class="close-text">Click anywhere to proceed</span>
              </Row>
            </Column>
          </Padding>
        </Modal>
      </div>

      <div onClick={() => setLoggedin(0)}>
        <Modal trigger={loggedin() === 1} background="#562020ff" color="#ffebebe6" opacity={0.8}>
          <Padding top={1} bottom={1} left={4} right={4}>
            <Column>
              <Row>
                <Box curved thickness={3} color="#ffebebe6" padding="1rem">
                  <h2>Login Failed</h2>
                </Box>
              </Row>

              <Row>
                <h3>{errorMessage()}</h3>
              </Row>

              <Row>
                <span class="close-text">Click anywhere to close</span>
              </Row>
            </Column>
          </Padding>
        </Modal>
      </div>

      <div onClick={() => setConnected(true)}>
        <Modal trigger={connected() === false} background="#562020ff" color="#ffebebe6" opacity={0.8}>
          <Padding top={1} bottom={1} left={4} right={4}>
            <Column>
              <Row>
                <Box curved thickness={3} color="#ffebebe6" padding="1rem">
                  <h2>Connection Error</h2>
                </Box>
              </Row>

              <Row>
                <h3>{errorMessage()}</h3>
              </Row>

              <Row>
                <span class="close-text">Click anywhere to close</span>
              </Row>
            </Column>
          </Padding>
        </Modal>
      </div>
    </>
  )
}
