import './Register.sass'
import { Logo, Link, Page, Row, Padding, Combobox, Box, Button, Modal, Column, QR, Input } from '../../components'
import { IoChevronBack } from 'solid-icons/io'
import { Show, createSignal, createEffect } from 'solid-js'
import { ofetch } from 'ofetch'
import { SHA3, SHA1 } from 'crypto-js'
import dayjs from 'dayjs'
import { FileField } from '@kobalte/core/file-field'
import { useNavigate } from '@solidjs/router'

export default () => {
  const API = import.meta.env.VITE_BACKEND
  const APPROVERNAME = import.meta.env.VITE_HEAD
  const assessors = JSON.parse(sessionStorage.getItem('assessors')!)
  const roles = ['ASSESSOR', 'APPROVER']

  const navigate = useNavigate()

  const [role, setRole] = createSignal('')
  const [name, setName] = createSignal('')
  const [password, setPassword] = createSignal('')
  const [hashPassword, setHashPassword] = createSignal('')
  const [id, setId] = createSignal<number>(0)
  const [signature, setSignature] = createSignal('')
  const [saved, setSaved] = createSignal(false)
  const [file, setFile] = createSignal<File[]>()
  const [base64image, setBase64image] = createSignal('')
  const [allow, setAllow] = createSignal(0)

  const getEmployeeId = async (val: string) => {
    try {
      setName(val)
      const id = await ofetch(API + 'get-employeeid/' + val, { parseResponse: JSON.parse })
      setId(parseInt(id.result))
      await checkRegistered()
    } catch {
      setId(0)
    }
  }

  const generateSignature = () => {
    if (role() === 'APPROVER') {
      setId(276)
      setName(APPROVERNAME)
    }
    const hash = SHA3(id().toString())
    setSignature(`Scan this using OCBO e-Sign Validator - scanid=${hash.toString()}`)

    try {
      register()
      setSaved(true)
      updateRegistered()
    } catch {
      setSaved(false)
    }
  }

  const register = async () => {
    await securePassword()
    const blob = new Blob(file())
    const base64 = await convertBase64(blob)
    setBase64image(base64 as string)

    await ofetch(API + 'post-registration', {
      method: 'POST',
      body: { data: id(), data2: hashPassword(), data3: signature(), data4: base64 },
    })
  }

  const getDate = () => {
    const today = new Date()
    const formattedDate = dayjs(today).format('YYYY-MM-DD HH:mm:ss Z')
    return formattedDate
  }

  const securePassword = async () => {
    const firstHashing = SHA1(password())
    const secondHashing = SHA3(firstHashing)
    const thirdHashing = SHA1(secondHashing)
    setHashPassword(thirdHashing.toString())
  }

  const convertBase64 = (blob: Blob) => {
    return new Promise((resolve, _) => {
      const reader = new FileReader()
      reader.onloadend = () => resolve(reader.result)
      reader.readAsDataURL(blob)
    })
  }

  const checkRegistered = async () => {
    const employeeid = id()

    try {
      const registered = await ofetch(API + 'check-registered/' + employeeid, { parseResponse: JSON.parse })
      if (registered.result > 0) {
        setAllow(1)
      } else {
        setAllow(2)
      }
    } catch {
      setAllow(2)
    }
  }

  const getAssessors = async (): Promise<string[]> => {
    let assessorsNameList: string[] = []

    try {
      const assessors = await ofetch(API + 'get-list-assessors', { parseResponse: JSON.parse })
      assessorsNameList = [...assessors.result]
      return [...assessorsNameList]
    } catch {
      return []
    }
  }

  const updateRegistered = async () => {
    const registered = await getAssessors()
    sessionStorage.setItem('assessors', JSON.stringify([...registered]))
  }

  const gotoIndex = () => {
    navigate('/')
  }

  createEffect(async () => {
    if (role() === 'APPROVER') {
      try {
        const registered = await ofetch(API + 'check-registered/' + 276, { parseResponse: JSON.parse })
        if (registered.result > 0) {
          setAllow(1)
        } else {
          setAllow(2)
        }
      } catch {
        setAllow(2)
      }
    }
  })

  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="#2f465cd7" background="#04040660">
                <Row>
                  <span class="box-title">Registration</span>
                </Row>
                <h4>Role</h4>
                <Combobox options={roles} placeholder="Select your role" value={role()} onChange={setRole} />

                <Show when={role() === 'ASSESSOR'}>
                  <h4>List of Assessors</h4>
                  <Combobox options={assessors} placeholder="Select your name" value={name()} onChange={(val) => getEmployeeId(val!)} />

                  <Show when={allow() === 2}>
                    <h4>Password</h4>
                    <Input value={password()} onChange={setPassword}></Input>
                    <h4>Upload Signature</h4>
                    <FileField class="filefield" maxFiles={1} onFileAccept={(data) => setFile(data)} accept=".jpg, .jpeg, .png, .webp, .avif">
                      <FileField.Dropzone class="filefield__dropzone">Drag and drop or click to upload file</FileField.Dropzone>
                      <FileField.HiddenInput />
                      <FileField.ItemList class="filefield__itemList">
                        {() => (
                          <FileField.Item class="filefield__item">
                            <FileField.ItemPreviewImage class="filefield__itemPreviewImage" />
                            <FileField.ItemName class="filefield__itemName" />
                            <FileField.ItemSize class="filefield__itemSize" />
                            <FileField.ItemDeleteTrigger class="filefield__itemDeleteTrigger" onClick={() => setFile()}>
                              Delete
                            </FileField.ItemDeleteTrigger>
                          </FileField.Item>
                        )}
                      </FileField.ItemList>
                    </FileField>

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

                      <Show when={!file() && !password()}>
                        <Row>
                          <span class="already-registered">Required password and signature</span>
                        </Row>
                      </Show>

                      <Show when={file() && !password()}>
                        <Row>
                          <span class="already-registered">Required password</span>
                        </Row>
                      </Show>

                      <Show when={!file() && password()}>
                        <Row>
                          <span class="already-registered">Required signature</span>
                        </Row>
                      </Show>
                    </Padding>
                  </Show>

                  <Show when={allow() === 1}>
                    <Padding top={2} bottom={0} left={0} right={0}>
                      <Row>
                        <span class="already-registered">Already Registered</span>
                      </Row>
                    </Padding>
                  </Show>
                </Show>

                <Show when={role() === 'APPROVER'}>
                  <h4>Name of Approver</h4>
                  <span class="approver-name">{APPROVERNAME}</span>

                  <h4>Password</h4>
                  <Input value={password()} onChange={setPassword}></Input>

                  <Show when={allow() === 2}>
                    <h4>Upload Signature</h4>
                    <FileField class="filefield" maxFiles={1} onFileAccept={(data) => setFile(data)} accept=".png">
                      <FileField.Dropzone class="filefield__dropzone">Drag and drop or click to upload file</FileField.Dropzone>
                      <FileField.HiddenInput />
                      <FileField.ItemList class="filefield__itemList">
                        {() => (
                          <FileField.Item class="filefield__item">
                            <FileField.ItemPreviewImage class="filefield__itemPreviewImage" />
                            <FileField.ItemName class="filefield__itemName" />
                            <FileField.ItemSize class="filefield__itemSize" />
                            <FileField.ItemDeleteTrigger class="filefield__itemDeleteTrigger" onClick={() => setFile()}>
                              Delete
                            </FileField.ItemDeleteTrigger>
                          </FileField.Item>
                        )}
                      </FileField.ItemList>
                    </FileField>

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

                      <Show when={file() && !password()}>
                        <Row>
                          <span class="already-registered">Required password</span>
                        </Row>
                      </Show>

                      <Show when={!file() && password()}>
                        <Row>
                          <span class="already-registered">Required signature</span>
                        </Row>
                      </Show>

                      <Show when={!file() && !password()}>
                        <Row>
                          <span class="already-registered">Required password and signature</span>
                        </Row>
                      </Show>
                    </Padding>
                  </Show>

                  <Show when={allow() === 1}>
                    <Padding top={2} bottom={0} left={0} right={0}>
                      <Row>
                        <span class="already-registered">Already Registered</span>
                      </Row>
                    </Padding>
                  </Show>
                </Show>
              </Box>
            </Row>
          </Padding>
        </Padding>
      </Page>

      <div onClick={gotoIndex}>
        <Modal trigger={saved()} background="#ffffffff" color="#000000e4" opacity={0.6}>
          <Padding top={1} bottom={1} left={4} right={4}>
            <Column>
              <Row>
                <Box curved thickness={3} color="black" padding="1rem">
                  <h2>e-Sign Registration Completed</h2>
                </Box>
              </Row>
              <Row>
                <h3>Representation of your digital signature</h3>
              </Row>

              <Row gap={1}>
                <QR value={signature()} width={10} />
                <section class="digital-sign-details">
                  <div>
                    <img class="digital-sign-details__image" src={base64image()} alt="Image of signature" />
                  </div>
                  <span>Digitally signed by:</span>
                  <span>{name()}</span>
                  <span>Date: {getDate()}</span>
                </section>
              </Row>

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