import { useNavigate } from '@solidjs/router'
import { IoChevronBack } from 'solid-icons/io'
import { createEffect, createSignal } from 'solid-js'
import { Show } from 'solid-js/web'
import { Box, Button, Clickable, Column, Combobox, Display, Input, Link, Logo, Modal, Padding, Page, Radio, Row, Switch } from '../../components'
import { _employeeId, _employeeName } from '../../stores/employee'
import { checkConnection, getApi, securePassword } from '../../utils/functions'
import { VsQuestion } from 'solid-icons/vs'
import './Login.sass'

export default () => {
  const APPROVERNAME = sessionStorage.getItem('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 [encryptionVersion, setEncryptionVersion] = createSignal('v1')
  const [openTooltip, setOpenTooltip] = createSignal(false)

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

    const employeeid = await getApi('get-employeeid', name())
    const dbpassword = await getApi('get-password', employeeid)
    const hashPassword = await securePassword(password(), encryptionVersion())

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

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

  // const securePassword = async () => {
  //   const firstHashing = SHA1(password())
  //   const secondHashing = SHA384(firstHashing.toString())
  //   const thirdHashing = SHA1(secondHashing.toString())

  //   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">
        <Display desktop tablet>
          <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">
                  <Row>
                    <span class="box-title">Login</span>
                  </Row>
                  <Row content='right' gap={0.5}>
                    <Switch label={`Enc ${encryptionVersion()}`} checked={encryptionVersion() === 'v1' ? false : true} onChange={() => encryptionVersion() === 'v1' ? setEncryptionVersion('v2') : setEncryptionVersion('v1')} />
                    <Clickable onClick={() => setOpenTooltip(true)}>
                      <VsQuestion size={28} style="cursor: pointer" />
                    </Clickable>
                  </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} width="25.75rem" />
                  </Show>
                  <Show when={role() === 'Approver'}>
                    <span class="approver-name">{APPROVERNAME}</span>
                  </Show>
                  <h4>Password</h4>
                  <Input
                    isPassword
                    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-login">Required password</span>
                      </Row>
                    </Show>

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

                    <Show when={password() && !name()}>
                      <Row>
                        <span class="required-login">Required name</span>
                      </Row>
                    </Show>
                  </Padding>
                </Box>
              </Row>
            </Padding>
          </Padding>
        </Display>
      </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>

      <div onClick={() => setOpenTooltip(false)}>
        <Modal trigger={openTooltip()} background="#252525ff" color="#dfe7fbf0" opacity={0.8} width='52rem'>
          <Padding top={1} bottom={1} left={1.5} right={1.5}>
            <section class='modal-tooltip'>
              <div class='modal-tooltip__group'>
                <span class='modal-tooltip__title'>Enc v1 (Encryption Version 1)</span>
                <span class='modal-tooltip__info'>Use this mode if your password has not been changed.</span>
                <span class='modal-tooltip__info'>It is recommended that you update your password after logging in. Open the 'Config' menu in the upper right.</span>
              </div>

              <div class='modal-tooltip__group'>
                <span class='modal-tooltip__title'>Enc v2 (Encryption Version 2)</span>
                <span class='modal-tooltip__info'>The new default password encryption.</span>
                <span class='modal-tooltip__info'>Use this mode if you've recently registered or changed your password.</span>
              </div>

              <div class='modal-tooltip__group'>
                <span class='modal-tooltip__note'>Note:</span>
                <span class='modal-tooltip__note-info'>To ensure security and privacy, avoid sharing your password.</span>
                <span class='modal-tooltip__note-info'>Your password's encryption is irreversible, which means it cannot be decrypted.</span>
                <span class='modal-tooltip__note-info'>Only encrypted passwords are saved in the database.</span>
                <span class='modal-tooltip__note-info'>Only you know your password. If forgotten, the account will be locked.</span>
                <span class='modal-tooltip__note-info'>If this happens, contact the IT department and request that your account be reset. You will be required to register again.</span>
              </div>

              <Row>
                <span class="close-text">Click anywhere to close</span>
              </Row>
            </section>

          </Padding>
        </Modal>
      </div>
    </>
  )
}
