import { Tabs } from '@kobalte/core/tabs'
import { useNavigate } from '@solidjs/router'
import dayjs from 'dayjs'
import { FaSolidThumbsUp, FaSolidUserGear } from 'solid-icons/fa'
import { FiLogOut } from 'solid-icons/fi'
import { VsRefresh } from 'solid-icons/vs'
import { createEffect, createSignal, onMount } from 'solid-js'
import { Show } from 'solid-js/web'
import { Box, Button, Clickable, Column, Input, Link, Logo, Modal, ModalButton, Padding, Page, Row } from '../../components/'
import { checkConnection, deleteApi, getApi, getApiMulti, getDateTime, lockData, postApi, saveNewName, saveNewPassword, securePassword, voidPopsApi, voidApi, statusPopsApi } from '../../utils/functions'
import { AiOutlineLoading3Quarters } from 'solid-icons/ai'
import './Main.sass'

const PESO = import.meta.env.VITE_PESO
const ID = sessionStorage.getItem('id')!
const PUBLICIP = import.meta.env.VITE_PUBLICIP
const BACKEND = import.meta.env.VITE_BACKEND

export default () => {
  const navigate = useNavigate()

  const [totalOp, setTotalOp] = createSignal('')
  const [assessor, setAssessor] = createSignal('')
  const [dateOp, setDateOp] = createSignal('')
  const [location, setLocation] = createSignal('')
  const [type, setType] = createSignal('')
  const [applicationId, setApplicationId] = createSignal(0)

  // const [assessorId, setAssessorId] = createSignal(0)

  // const [gflgu, setGflgu] = createSignal<number[]>([])
  // const [gfdpwh, setGfdpwh] = createSignal<number[]>([])
  // const [tfbo, setTfbo] = createSignal<number[]>([])

  // const [descriptionList, setDescriptionList] = createSignal<string[]>([])
  // const [amountList, setAmountList] = createSignal<string[]>([])
  // const [dateOpList, setDateOpList] = createSignal<string[]>([])

  const [applicationListElectrical, setApplicationListElectrical] = createSignal<string[]>([])
  const [nameListElectrical, setNameListElectrical] = createSignal<string[]>([])
  const [applicationListOccupancy, setApplicationListOccupancy] = createSignal<string[]>([])
  const [nameListOccupancy, setNameListOccupancy] = createSignal<string[]>([])

  const [errorMessage, setErrorMessage] = createSignal('')
  const [connected, setConnected] = createSignal(true)
  const [approved, setApproved] = createSignal(false)
  const [approvedApplication, setApprovedApplication] = createSignal('')

  const [employeeId, setEmployeeId] = createSignal(0)
  const [employeeName, setEmployeeName] = createSignal('')

  // const [apology, setApology] = createSignal(false)
  const [openConfig, setOpenConfig] = createSignal(false)
  const [configEncPassword, setConfigEncPassword] = createSignal('')
  const [configNewName, setConfigNewName] = createSignal('')
  const [configPassword, setConfigPassword] = createSignal('')
  const [configNewPassword, setConfigNewPassword] = createSignal('')
  const [configNewEncPassword, setConfigNewEncPassword] = createSignal('')
  const [configError, setConfigError] = createSignal('')
  const [postError, setPostError] = createSignal(false)

  const [configNotification, setConfigNotification] = createSignal(false)
  const [isIncomplete, setIsIncomplete] = createSignal(false)
  const [isLoading, setIsLoading] = createSignal(false)
  const [loadingText, setLoadingText] = createSignal('')

  let bldgadditional = false

  const getListForApproval = async () => {
    const responseE = await getApiMulti('get-listopapproval-electrical')
    setApplicationListElectrical(responseE.result)
    setNameListElectrical(responseE.result2)

    const responseO = await getApiMulti('get-listopapproval-occupancy')
    setApplicationListOccupancy(responseO.result)
    setNameListOccupancy(responseO.result2)
  }

  const getListForApprovalElectrical = async () => {
    // setIsLoading(true)
    const responseE = await getApiMulti('get-listopapproval-electrical')
    setApplicationListElectrical(responseE.result)
    setNameListElectrical(responseE.result2)
    // setIsLoading(false)
  }

  const getListForApprovalOccupancy = async () => {
    // setIsLoading(true)
    const responseO = await getApiMulti('get-listopapproval-occupancy')
    setApplicationListOccupancy(responseO.result)
    setNameListOccupancy(responseO.result2)
    // setIsLoading(false)
  }

  const load = async (division: string) => {
    setConnected(await checkConnection())
    if (connected() === false) {
      setErrorMessage('Could not gather list of applications')
      return
    }
    setIsLoading(true)
    setLoadingText('Downloading Data')

    await getPassword()

    if (division === 'electrical') {
      await getListForApprovalElectrical()
    }
    if (division === 'occupancy') {
      await getListForApprovalOccupancy()
    } else {
      await getListForApproval()
    }
    setIsLoading(false)
  }

  const getopdetails = async (division: string, applicationNo: string) => {
    let op
    if (division === 'electrical') {
      op = await getApiMulti('get-opdetails-electrical', applicationNo)
    } else if (division === 'occupancy') {
      op = await getApiMulti('get-opdetails-occupancy', applicationNo)
    }

    if (isDetailsComplete(op.result, op.result2, op.result3, op.result4, op.result5, op.result6)) {
      setIsIncomplete(false)
      setLocation(op.result[0])
      setType(op.result2[0])
      setAssessor(op.result3[0])
      const total = calculateTotal(op.result4)
      const formattedTotal = new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(total)
      setTotalOp(formattedTotal)
      setDateOp(dayjs(op.result5[0]).format('MMMM DD, YYYY'))
      setApplicationId(op.result6[0])
    } else {
      setIsIncomplete(true)
    }
  }

  const isDetailsComplete = (result: string[], result2: string[], result3: string[], result4: string[], result5: string[], result6: string[]) => {
    return result.length > 0 && result2.length > 0 && result3.length > 0 && result4.length > 0 && result5.length > 0 && result6.length > 0 ? true : false
  }

  const calculateTotal = (list: number[]) => {
    const total = list.map((item) => parseFloat(item.toString())).reduce((acc, curr) => acc + curr, 0)
    return total
  }

  // const sample = async () => {
  //   const data = await lockData('asdasdsadsad')
  //   console.log(data)
  // }

  const approveHandler = async (division: string, application: string) => {
    let signed: boolean = false
    let forprinting: boolean = false
    let updateOrderofpayment: boolean = false

    let popsExist: boolean = false
    let popsPaid: boolean = false

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

    setIsLoading(true)
    setLoadingText('Processing Data')

    if (division === 'electrical') {
      if (BACKEND.includes('localhost')) {
        const status = await checkStatusPopsLocal(application)
        if (status.result > 0) popsExist = true
        if (status.result2 > 0) popsPaid = true
      } else {
        const status = await await statusPopsOp(application)
        if (status.message === 'Success') popsExist = true
        if (status.pops_paid === true) popsPaid = true
      }

      if (popsExist) {
        if (popsPaid) {
          setPostError(true)
          setErrorMessage('Application Already Paid')
          return
        } else {
          if (BACKEND.includes('localhost')) {
            const voidOP = await voidPopsOpLocal(application)

            if (!voidOP) {
              setPostError(true)
              setErrorMessage('POPS Record found but failed to void')
              return
            }
          } else {
            const voidOP = await voidPopsOp(application)

            if (voidOP.toUpper().includes('ERROR')) {
              setPostError(true)
              setErrorMessage('POPS Record found but failed to void')
              return
            }
          }
        }
      }

      await postPops(division, application)
      // const popsResult = await checkPops(application)
      const dataLocked = await lockOpData(division, application)

      if (dataLocked) {
        signed = await setNewStatus(division, 'ELECTRICAL ORDER OF PAYMENT APPROVED AND SIGNED', '170', 'ELECOPAPPROVEDSIGNED', 1)
        updateDocflow(division, application, 'FOR ELECTRICAL ORDER OF PAYMENT APPROVAL')
        if (!signed) return

        forprinting = await setNewStatus(division, 'FOR ELECTRICAL ORDER OF PAYMENT PRINTING', '95', 'ELECOPPRINT', 0)
        if (!forprinting) return

        updateOrderofpayment = await updateOp(division)

        if (updateOrderofpayment) {
          postTransaction()
          setApprovedApplication(application)
          setApproved(true)
        }
      } else {
        setPostError(true)
        setErrorMessage('Error on posting on POPS Server, please try again')
        return
      }
    } else if (division === 'occupancy') {
      const additionalResult = await getApi('check-bldgadditional-approval', application)
      bldgadditional = additionalResult > 0

      await voidPopsOp(application)
      await postPops(division, application)
      const popsResult = await checkPops(application)
      const lockResult = await lockOpData(division, application)

      if (popsResult && lockResult) {
        signed = await setNewStatus(division, 'OCCUPANCY ORDER OF PAYMENT APPROVED AND SIGNED', '172', 'OCCOPAPPROVEDSIGNED', 1)
        updateDocflow(division, application, 'FOR OCCUPANCY RECOMMENDING APPROVAL')
        if (bldgadditional) {
          const neededToUpdate = await checkApproval(application, 'FOR ADDITIONAL ORDER OF PAYMENT RECOMMENDING APPROVAL')
          if (!neededToUpdate) updateDocflow(division, application, 'FOR ADDITIONAL ORDER OF PAYMENT RECOMMENDING APPROVAL')
        }
        if (!signed) return

        forprinting = await setNewStatus(division, 'APPROVED FOR PRINTING OF BUREAU OF FIRE AND ORDER OF PAYMENT', '23', 'OCORDEROFPAYMENT', 0)
        if (!forprinting) return

        updateOrderofpayment = await updateOp(division)

        if (updateOrderofpayment) {
          postTransaction()
          setApprovedApplication(application)
          setApproved(true)
        }
      } else {
        setPostError(true)
        setErrorMessage('Error on posting on POPS Server, please try again')
        return
      }
      setIsLoading(false)
    }
  }

  // const approveElectrical = async (division: string, application: string) => {
  //   let signed: boolean = false
  //   let forprinting: boolean = false
  //   let updateOrderofpayment: boolean = false

  //   await postPops(division, application)
  //   const popsResult = await checkPops(application)
  //   const lockResult = await lockOpData(division, application)

  //   if (popsResult && lockResult) {
  //     signed = await setNewStatus(division, 'ELECTRICAL ORDER OF PAYMENT APPROVED AND SIGNED', '170', 'ELECOPAPPROVEDSIGNED', 1)
  //     updateDocflow(division, application, 'FOR ELECTRICAL ORDER OF PAYMENT APPROVAL')
  //     if (!signed) return

  //     forprinting = await setNewStatus(division, 'FOR ELECTRICAL ORDER OF PAYMENT PRINTING', '95', 'ELECOPPRINT', 0)
  //     if (!forprinting) return

  //     updateOrderofpayment = await updateOp(division)

  //     if (updateOrderofpayment) {
  //       postTransaction()
  //       setApprovedApplication(application)
  //       setApproved(true)
  //     }
  //   } else {
  //     setPostError(true)
  //     setErrorMessage('Error on posting on POPS Server, please try again')
  //     return
  //   }
  // }

  const lockOpData = async (division: string, application: string) => {
    const dataToLock = await getApi(`get-opdata-${division}`, application)
    const lockedData = await lockData(dataToLock)
    const fixedLockedData = lockedData.replace(/\//g, '~')
    const saveLockedData = await postApi('save-lockdata', { data: application, data2: fixedLockedData })
    return saveLockedData
  }

  const voidPopsOp = async (application: string) => {
    const response = await voidPopsApi(application)
    return response
  }

  const voidPopsOpLocal = async (application: string) => {
    const response = await voidApi('void-op-local', { data: application })
    return response
  }

  const checkStatusPopsLocal = async (application: string) => {
    const response = await getApiMulti('check-statuspops-local', application)
    return response
  }

  const statusPopsOp = async (application: string) => {
    const response = await statusPopsApi(application)
    return response
  }

  const returnAssessment = async (division: string, application: string) => {
    const id = await getApplicationById(division, application)
    setApplicationId(id)
    let forassessment

    if (division === 'electrical') {
      forassessment = await setNewStatus(division, 'FOR ELECTRICAL ASSESSMENT', '88', 'ELECASSESSMENT', 0)
    } else {
      forassessment = await setNewStatus(division, 'OCCUPANCY ASSESSMENT', '21', 'OCASSESSMENT', 0)
    }
    if (!forassessment) return

    if (division === 'electrical') {
      updateDocflow(division, application, 'FOR ELECTRICAL ORDER OF PAYMENT APPROVAL')
    } else {
      updateDocflow(division, application, 'FOR OCCUPANCY RECOMMENDING APPROVAL')
    }

    await deleteOrderofPayment(division, id)
    await load('all')
  }

  const getApplicationById = async (division: string, application: string) => {
    const id = await getApi(`get-idbyapplication-${division}`, application)
    return parseInt(id)
  }

  const deleteOrderofPayment = async (division: string, id: number) => {
    const deleteOp = await deleteApi(`delete-orderofpayment-${division}`, {
      data: id,
    })
    return deleteOp
  }

  const setNewStatus = async (division: string, status: string, tag: string, tagword: string, approved: number) => {
    // const today = new Date()
    const today = await getDateTime()
    const formattedDate = dayjs(today).format('YYYY-MM-DD HH:mm:ss')
    const statusid = parseInt(applicationId().toString())

    if (division === 'electrical') {
      return await postApi('post-newstatus-electrical', { data: statusid, data2: formattedDate, data3: status, data4: tag, data5: tagword, data6: parseInt(approved.toString()), data7: parseInt(ID) })
    } else {
      return await postApi('post-newstatus-occupancy', { data: statusid, data2: formattedDate, data3: status, data4: tag, data5: tagword, data6: parseInt(approved.toString()), data7: parseInt(ID) })
    }
  }

  const updateOp = async (division: string) => {
    if (division === 'electrical') {
      return await postApi('update-opapproved-electrical', { data: parseInt(applicationId().toString()) })
    } else {
      const occupancy = await postApi('update-opapproved-occupancy', { data: parseInt(applicationId().toString()) })
      if (bldgadditional) await postApi('update-opapproved-bldgadditional', { data: parseInt(applicationId().toString()) })
      return occupancy
    }
  }

  const postPops = async (division: string, application: string) => {
    let response

    if (division === 'electrical') {
      response = await getApiMulti('get-popsdetails-electrical', application)
    } else if (division === 'occupancy') {
      response = await getApiMulti('get-popsdetails-occupancy', application)
    }

    const customerid = response.result2[0]
    const customerName = response.result3[0]
    const location = response.result4[0]
    const amountList = response.result5
    const lguList = response.result6
    const dpwhList = response.result7
    const boList = response.result8
    const codeList = response.result9

    const today = await getDateTime()
    const formattedDate = dayjs(today).format('YYYY-MM-DD')
    const formattedDatewithTime = dayjs(today).format('YYYY-MM-DD HH:mm:ss')

    for (let i = 0; i < response.result.length; i++) {
      await postApi('post-pops', { data: application, data2: formattedDate, data3: customerid, data4: customerName, data5: location, data6: codeList[i], data7: amountList[i], data8: assessor(), data9: formattedDatewithTime, data10: lguList[i], data11: dpwhList[i], data12: boList[i], data13: PUBLICIP })
    }
  }

  const checkPops = async (application: string) => {
    const response = await getApi('check-popsrecord', application)
    const result = response

    return parseInt(result) > 0
  }

  // const calculateAmounts = () => {
  //   const amounts: string[] = amountList()
  //   let gflguList: number[] = []
  //   let gfdpwhList: number[] = []
  //   let tfboList: number[] = []

  //   for (let i = 0; i < amounts.length; i++) {
  //     const gflgu = parseFloat(amounts[i]) * 0.8
  //     const gfdpwh = parseFloat(amounts[i]) * 0.05
  //     const tfbo = parseFloat(amounts[i]) * 0.15

  //     const roundedGflgu = parseFloat(gflgu.toFixed(2))
  //     const roundedGfdpwh = parseFloat(gfdpwh.toFixed(2))
  //     const roundedTfbo = parseFloat(tfbo.toFixed(2))

  //     gflguList.push(roundedGflgu)
  //     gfdpwhList.push(roundedGfdpwh)
  //     tfboList.push(roundedTfbo)
  //   }

  //   setGflgu(gflguList)
  //   setGfdpwh(gfdpwhList)
  //   setTfbo(tfboList)
  // }

  const closeNotification = async () => {
    setApproved(false)
    await load('all')
  }

  const removeEmployee = () => {
    sessionStorage.removeItem('id')
    sessionStorage.removeItem('name')
  }

  const checkLogged = async () => {
    const idStore = sessionStorage.getItem('id')
    const nameStore = sessionStorage.getItem('name')
    setEmployeeId(parseInt(idStore!))
    setEmployeeName(nameStore!)

    if (employeeId() === 0 || employeeId().toString() === 'NaN') {
      removeEmployee()
      navigate('/', { replace: true })
      return false
    }
    return true
  }

  const deleteHeadName = async () => {
    sessionStorage.removeItem('head')
    sessionStorage.removeItem('headid')
  }

  const geteSignId = async () => {
    try {
      const response = await getApi('get-esignid', ID)
      return response
    } catch {
      return 0
    }
  }

  const postTransaction = async () => {
    const id = await geteSignId()
    const today = await getDateTime()
    const formattedDate = dayjs(today).format('YYYY-MM-DD HH:mm:ss')

    await postApi('post-esigntransaction', { data: parseInt(id), data2: approvedApplication(), data3: formattedDate })
  }

  const updateDocflow = async (division: string, application: string, status: string) => {
    await postApi(`update-docflow-${division}`, { data: status, data2: application })
  }

  const refresh = async (division: string) => {
    if (division === 'electrical') {
      await load('electrical')
    } else if (division === 'occupancy') {
      await load('occupancy')
    } else {
      await load('all')
    }
  }

  const checkApproval = async (application: string, status: string) => {
    const response = await getApi('check-approval', status, application)
    return response
  }

  const getPassword = async () => {
    const response = await getApi('get-password', ID)
    setConfigEncPassword(response)
  }

  const checkCurrentPassword = async () => {
    const encCurrentPasswordV1 = await securePassword(configPassword(), 'v1')
    const encCurrentPasswordV2 = await securePassword(configPassword(), 'v2')

    if (encCurrentPasswordV1 === configEncPassword() || encCurrentPasswordV2 === configEncPassword()) {
      if (configNewPassword() === '') {
        setConfigError('New Password not provided')
        setConfigNewEncPassword('')
      } else {
        setConfigError('')
        encryptNewPassword()
      }
    } else {
      setConfigError('Invalid Password')
      setConfigNewEncPassword('')
    }
  }

  const encryptNewPassword = async () => {
    const encNewPassword = await securePassword(configNewPassword(), 'v2')
    setConfigNewEncPassword(encNewPassword)
  }

  const saveConfig = async () => {
    if (configNewName() !== '') await saveNewName(parseInt(ID), configNewName())
    if (configNewPassword() !== '') await saveNewPassword(parseInt(ID), configNewEncPassword())

    setConfigNotification(true)
  }

  // const saveNewName = async (name: string) => {
  //   await postApi('update-name', {
  //     data: parseInt(ID),
  //     data2: name
  //   })
  // }

  // const saveNewPassword = async (password: string) => {
  //   await postApi('update-password', {
  //     data: parseInt(ID),
  //     data2: password
  //   })
  // }

  const logout = async () => {
    removeEmployee()
    navigate('/')
  }

  const updateHeadName = async () => {
    const response = await getApi('get-head')

    setEmployeeName(response!)
  }

  // const gotoProfile = () => {
  //   navigate('/profile')
  // }

  const closeConfig = async () => {
    await updateHeadName()
    setConfigNotification(false)
    setOpenConfig(false)

    setConfigEncPassword('')
    setConfigNewName('')
    setConfigPassword('')
    setConfigNewPassword('')
    setConfigNewEncPassword('')
    setConfigError('')
  }

  onMount(async () => {
    await deleteHeadName()
    const logged = await checkLogged()

    if (logged) {
      await load('all')
    }
  })

  createEffect(() => {
    if (configPassword() !== '') {
      checkCurrentPassword()
    } else {
      checkCurrentPassword()
    }

    if (configNewPassword() !== '') {
      encryptNewPassword()
    } else {
      encryptNewPassword()
    }
  })

  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>

            <Row content="left" gap={1.75}>
              <Box curved thickness={0} padding="1.25rem 2.25rem" background="#0f131d56">
                <span class="name">{employeeName()}</span>
              </Box>
              <Clickable onClick={() => setOpenConfig(true)}>
                <Row gap={0.25}>
                  <FaSolidUserGear size={20} />
                  <span>Config</span>
                </Row>
              </Clickable>
              <Clickable onClick={logout}>
                <Row gap={0.25}>
                  <FiLogOut size={20} />
                  <span>Logout</span>
                </Row>
              </Clickable>
            </Row>
          </Row>
          <Row content="center">
            <Tabs aria-label="Main navigation" class="tabs">
              <Row>
                <Tabs.List class="tabs__list">
                  <Tabs.Trigger class="tabs__trigger" value="building">
                    Building
                  </Tabs.Trigger>
                  <Tabs.Trigger class="tabs__trigger" value="occupancy">
                    Occupancy
                  </Tabs.Trigger>
                  <Tabs.Trigger class="tabs__trigger" value="electrical">
                    Electrical
                  </Tabs.Trigger>
                  <Tabs.Indicator class="tabs__indicator" />
                </Tabs.List>
              </Row>

              <Tabs.Content class="tabs__content" value="building">
                <Row>
                  {/* <h2>List of Ready to Approve and Sign Building Order of Payments</h2> */}
                  <Padding top={2} bottom={0} left={0} right={0}>
                    <Box curved thickness={0} background="#602a2abf" padding="1rem 2rem">
                      <h2>Under Development</h2>
                    </Box>
                  </Padding>
                </Row>

                <Row>
                  <table class="table">
                    <thead>
                      {/* <tr>
                        <th>Application Number</th>
                        <th>Name</th>
                        <th style="text-align: center">Show Details</th>
                      </tr> */}
                    </thead>
                    <tbody></tbody>
                  </table>
                </Row>
              </Tabs.Content>
              <Tabs.Content class="tabs__content" value="occupancy">
                <Row>
                  <h2>List of Ready to Approve and Sign in Occupancy Order of Payments</h2>
                </Row>

                <Padding top={0} bottom={0} right={10} left={0}>
                  <Row content="right">
                    <Button label="Refresh Data" edges="curved" design="bo-primary" icon={VsRefresh} onClick={() => refresh('occupancy')}></Button>
                  </Row>
                </Padding>

                <Row>
                  <table class="table">
                    <thead>
                      <tr>
                        <th>Application Number</th>
                        <th>Name</th>
                        <th style="text-align: center">Show Details</th>
                      </tr>
                    </thead>
                    <tbody>
                      {applicationListOccupancy().map((item: string, index: number) => (
                        <tr>
                          <td>{item}</td>
                          <td>{nameListOccupancy()[index]}</td>

                          <td>
                            <ModalButton
                              class="modal"
                              label="Show Details"
                              design="bo-link"
                              background="#121e2acc"
                              color="#ffffffec"
                              function={async () => {
                                await getopdetails('occupancy', item)
                              }}
                            >
                              <Padding top={0} left={2} right={2} bottom={0}>
                                <span class="modal__application-number">{item}</span>

                                <Padding top={1} left={0} right={0} bottom={0}>
                                  <section class="modal__row">
                                    <span class="modal__row__label">Name of Applicant:</span>
                                    <span class="modal__row__detail">{nameListOccupancy()[index]}</span>
                                  </section>

                                  <section class="modal__row">
                                    <span class="modal__row__label">Location:</span>
                                    <span class="modal__row__detail">{location()}</span>
                                  </section>

                                  <section class="modal__row">
                                    <span class="modal__row__label">Type:</span>
                                    <span class="modal__row__detail">{type().toUpperCase()}</span>
                                  </section>

                                  <section class="modal__row">
                                    <span class="modal__row__label">Assessed By:</span>
                                    <span class="modal__row__detail">{assessor()}</span>
                                  </section>

                                  <section class="modal__row">
                                    <span class="modal__row__label">Date Assessed:</span>
                                    <span class="modal__row__detail">{dateOp().toUpperCase()}</span>
                                  </section>

                                  <section class="modal__row">
                                    <span class="modal__row__label">Total Fee:</span>
                                    <span class="modal__row__detail__price">
                                      {PESO} {totalOp()}
                                    </span>
                                  </section>
                                </Padding>

                                <Row padding="2rem 0 0 0">
                                  <Button wide label="Approve" edges="curved" design="bo-primary" onClick={() => approveHandler('occupancy', item)}></Button>
                                  <span class="modal__cancel">Click anywhere to cancel</span>
                                </Row>
                              </Padding>
                            </ModalButton>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </Row>
              </Tabs.Content>
              <Tabs.Content class="tabs__content" value="electrical">
                <Row>
                  <h2>List of Ready to Approve and Sign in Electrical Order of Payments</h2>
                </Row>

                <Padding top={0} bottom={0} right={10} left={0}>
                  <Row content="right">
                    <Button label="Refresh Data" edges="curved" design="bo-primary" icon={VsRefresh} onClick={() => refresh('electrical')}></Button>
                  </Row>
                </Padding>

                <Row>
                  <Show when={isLoading()}>
                    <Padding top={2} bottom={0} right={10} left={10}>
                      <Column gap={1}>
                        <AiOutlineLoading3Quarters class="loading-spinner" size={42} opacity={0.8} />
                        <span>{loadingText()}</span>
                      </Column>
                    </Padding>
                  </Show>
                  <Show when={!isLoading()}>
                    <table class="table">
                      <thead>
                        <tr>
                          <th>Application Number</th>
                          <th>Name</th>
                          <th style="text-align: center">Show Details</th>
                        </tr>
                      </thead>
                      <tbody>
                        {applicationListElectrical().map((item: string, index: number) => (
                          <tr>
                            <td>{item}</td>
                            <td>{nameListElectrical()[index]}</td>

                            <td>
                              <ModalButton
                                class="modal"
                                label="Show Details"
                                design="bo-link"
                                background="#121e2acc"
                                color="#ffffffec"
                                function={async () => {
                                  await getopdetails('electrical', item)
                                }}
                              >
                                <Show when={isIncomplete()}>
                                  <Padding top={0} left={2} right={2} bottom={0}>
                                    <span class="modal__application-number">{item}</span>

                                    <Padding top={1} left={0} right={0} bottom={0}>
                                      <Column padding="0 0 1rem 0">
                                        <Box curved thickness={3} color="#c85656" padding="1rem">
                                          <h2 class="incomplete__error">Signing Error</h2>
                                        </Box>
                                        <h3 class="incomplete__error">Missing Data Detected</h3>
                                      </Column>

                                      <div class="incomplete">
                                        <Column>
                                          <span class="incomplete__text">Some required information is missing from the application details</span>
                                          <span class="incomplete__text">Please return to Assessment to complete the required fields</span>
                                        </Column>
                                      </div>
                                    </Padding>
                                    <Column padding="1rem 0 0 0">
                                      <Button wide label="Return to Assessment" edges="curved" design="bo-primary" onClick={() => returnAssessment('electrical', item)} />
                                      <span class="modal__cancel">Click anywhere to cancel</span>
                                    </Column>
                                  </Padding>
                                </Show>

                                <Show when={!isIncomplete()}>
                                  <Padding top={0} left={2} right={2} bottom={0}>
                                    <span class="modal__application-number">{item}</span>

                                    <Padding top={1} left={0} right={0} bottom={0}>
                                      <section class="modal__row">
                                        <span class="modal__row__label">Name of Applicant:</span>
                                        <span class="modal__row__detail">{nameListElectrical()[index]}</span>
                                      </section>

                                      <section class="modal__row">
                                        <span class="modal__row__label">Location:</span>
                                        <span class="modal__row__detail">{location()}</span>
                                      </section>

                                      <section class="modal__row">
                                        <span class="modal__row__label">Type:</span>
                                        <span class="modal__row__detail">{type().toUpperCase()}</span>
                                      </section>

                                      <section class="modal__row">
                                        <span class="modal__row__label">Assessed By:</span>
                                        <span class="modal__row__detail">{assessor()}</span>
                                      </section>

                                      <section class="modal__row">
                                        <span class="modal__row__label">Date Assessed:</span>
                                        <span class="modal__row__detail">{dateOp().toUpperCase()}</span>
                                      </section>

                                      <section class="modal__row">
                                        <span class="modal__row__label">Total Fee:</span>
                                        <span class="modal__row__detail__price">
                                          {PESO} {totalOp()}
                                        </span>
                                      </section>
                                    </Padding>

                                    <Column padding="2rem 0 0 0">
                                      <Button wide label="Approve" edges="curved" design="bo-primary" onClick={() => approveHandler('electrical', item)} />
                                      <span class="modal__cancel">Click anywhere to cancel</span>
                                    </Column>
                                  </Padding>
                                </Show>
                              </ModalButton>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </Show>
                </Row>
              </Tabs.Content>
            </Tabs>
          </Row>
        </Padding>
      </Page>

      {/* <div onClick={() => setApproved(false)}>
        <Modal trigger={approved()} background="#123220ff" color="#cdfbe1f0" opacity={0.8}>
          <Padding top={1} bottom={1} left={2} right={2}>
            <Column>
              <Row gap={4}>
                <FaSolidThumbsUp size={75} />
                <Box curved thickness={3} color="#cdfbe1f0" padding="1rem">
                  <span class="approval">Approved</span>
                </Box>
              </Row>
              <Row padding="2rem 0 0 0">
                <h2>{approvedApplication()}</h2>
              </Row>

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

      <div onClick={closeNotification}>
        <Modal trigger={approved()} background="#123220ff" color="#cdfbe1f0" opacity={0.8}>
          <Padding top={1} bottom={1} left={2} right={2}>
            <Column>
              <Row gap={4}>
                <FaSolidThumbsUp size={75} />
                <Box curved thickness={3} color="#cdfbe1f0" padding="1rem">
                  <span class="approval">Approved</span>
                </Box>
              </Row>
              <Row padding="2rem 0 0 0">
                <h2>{approvedApplication()}</h2>
              </Row>

              <Row>
                <span class="close-text">Click anywhere to proceed</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>

      <Modal trigger={openConfig()} background="#16212c" color="#ffffffed" opacity={0.8} width="30rem">
        <Padding top={1} bottom={1} left={4} right={4}>
          <section class="config">
            <div class="config__row">
              Name:
              <span>{employeeName()}</span>
            </div>

            <div class="config__edit">
              <span class="config__edit__title">Change Displayed Name</span>
              <Input value={configNewName()} onChange={setConfigNewName} placeholder="Enter new name" />
              <span class="config__edit__info">Leave blank to remain unchanged.</span>
            </div>

            <div class="config__edit">
              <span class="config__edit__title">Change Password</span>
              <Input isPassword value={configPassword()} onChange={setConfigPassword} placeholder="Enter current password" />
              <Input isPassword value={configNewPassword()} onChange={setConfigNewPassword} placeholder="Enter new password" />

              <Show when={configNewPassword().length !== 0}>
                <span style="padding: 1.75rem 0 0 0">Current Encrypted Password:</span>
                <span>{configEncPassword()}</span>

                <span style="padding: 0.75rem 0 0 0">New Encrypted Password:</span>
                <span>{configNewEncPassword()}</span>
              </Show>
            </div>

            <Show when={configError() !== ''}>
              <span class="required-config">{configError()}</span>
              <Button label="Cancel" edges="curved" design="bo-danger" onClick={() => setOpenConfig(false)} wide />
            </Show>

            <div class="config__button">
              <Show when={configError() === ''}>
                <Button label="Confirm" edges="curved" design="bo-primary" onClick={saveConfig} wide />
                <Button label="Cancel" edges="curved" design="bo-danger" onClick={() => setOpenConfig(false)} wide />
              </Show>
            </div>
          </section>
        </Padding>
      </Modal>

      <div onClick={closeConfig}>
        <Modal trigger={configNotification() === true} background="#123220ff" color="#cdfbe1f0" opacity={0.8}>
          <Padding top={1} bottom={1} left={4} right={4}>
            <Column>
              <Row gap={4}>
                <Box curved thickness={3} color="#cdfbe1f0" padding="1rem">
                  <span class="approval">Account Updated</span>
                </Box>
              </Row>

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

      <div onClick={() => setPostError(false)}>
        <Modal trigger={postError() === true} 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>Approval and Signing Error</h2>
                </Box>
              </Row>

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

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