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, Combobox, Input, Link, Logo, Modal, ModalButton, Padding, Page, Row } from '../../components/index.ts'
import {
  _additional,
  _additionalAmountList,
  _additionalCodeList,
  _additionalFeeList,
  _additionalUnitList,
  _amountList,
  _applicationNo,
  _approvedDate,
  _assessedDate,
  _assessor,
  _assessorid,
  _codeList,
  _date,
  _feeList,
  _floorArea,
  _location,
  _name,
  _optn,
  _signatureApprover,
  _signatureAssessor,
  _totalUnits,
  _type,
  _units,
} from '../../stores/pdfinfo.ts'
import { checkConnection, createPdfElectrical, createPdfOccupancy, deleteApi, getApi, getApiMulti, getDateTime, postApi, saveNewName, saveNewPassword, securePassword, statusPopsApi, voidPopsApi } from '../../utils/functions/index.ts'
import { AiOutlineLoading3Quarters } from 'solid-icons/ai'
import './Assessor.sass'

const PESO = import.meta.env.VITE_PESO
const BACKEND = import.meta.env.VITE_BACKEND

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

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

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

  const [errorMessage, setErrorMessage] = createSignal('')
  const [connected, setConnected] = createSignal(true)
  const [printed, setPrinted] = createSignal(false)
  const [printedApplication, setPrintedApplication] = createSignal('')

  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 [configNotification, setConfigNotification] = createSignal(false)

  const [isBuilding, setIsBuilding] = createSignal(false)
  const [isOccupancy, setIsOccupancy] = createSignal(false)
  const [isElectrical, setIsElectrical] = createSignal(false)

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

  const [filter, setFilter] = createSignal('')

  // const listType = ['Print', 'Reprint (No Change)', 'Void and Reapprove']
  const listType = ['Print', 'Reprint (No Change)']
  const [selectedType, setSelectedType] = createSignal('Print')

  const [voidError, setVoidError] = createSignal(false)
  const [isLoading, setIsLoading] = createSignal(false)
  const [loadingText, setLoadingText] = createSignal('')

  let bldgadditional = false

  const checkAccess = async (access: string) => {
    const response = await getApi('check-access', access, employeeId())
    const result = response
    if (result > 0) return true
    else return false
  }

  const getPrintDetails = async (division: string, id: number) => {
    let response
    if (selectedType() === 'Print') response = await getApiMulti(`get-printdetails-${division}`, id)
    else response = await getApiMulti(`get-reprintdetails-${division}`, id)

    const applicationno = response.result
    const date = response.result2
    const location = response.result3
    const name = response.result8
    const type = `${response.result4} - ${response.result5}`
    const assessor = response.result7
    const units = response.result6
    let totalUnits = 0
    let floorArea = 0

    if (division === 'occupancy') {
      totalUnits = response.result9
      floorArea = response.result10

      _totalUnits.set(totalUnits)
      _floorArea.set(floorArea)
    }

    _optn.set(`M${applicationno.split('-')[0]}${applicationno.split('-')[1]}`)
    _applicationNo.set(applicationno)
    _date.set(dayjs(date).format('MMMM DD, YYYY'))
    _name.set(name)
    _location.set(location)
    _type.set(type)
    _assessor.set(assessor)
    _assessorid.set(employeeId())
    _units.set(units)
  }

  const getPrintDetailsFees = async (division: string, id: number) => {
    let response
    if (selectedType() === 'Print') response = await getApiMulti(`get-printdetailsfees-${division}`, id)
    else response = await getApiMulti(`get-reprintdetailsfees-${division}`, id)

    const feeList = response.result
    const accountCodeList = response.result2
    const amountList = response.result3

    _feeList.set(feeList)
    _codeList.set(accountCodeList)
    _amountList.set(amountList)

    _additional.set(false)

    if (division === 'occupancy' && bldgadditional) {
      const response = await getApiMulti('get-printdetailsfees-bldgadditional', id)
      const feeList = response.result
      const accountCodeList = response.result2
      const amountList = response.result3
      const unitList = response.result4

      _additional.set(true)
      _additionalFeeList.set(feeList)
      _additionalCodeList.set(accountCodeList)
      _additionalAmountList.set(amountList)
      _additionalUnitList.set(unitList)
    }
  }

  // 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 () => {
    setPrinted(false)
    await checkDivision()
    if (isBuilding()) await getListForPrinting('building')
    if (isOccupancy()) await getListForPrinting('occupancy')
    if (isElectrical()) await getListForPrinting('electrical')
  }

  const checkDivision = async () => {
    const building = await checkAccess('BUILDING ORDER OF PAYMENT')
    setIsBuilding(building)

    const occupancy = await checkAccess('OCCUPANCY ORDER OF PAYMENT')
    setIsOccupancy(occupancy)

    const electrical = await checkAccess('ELECTRICAL ASSESSMENT')
    setIsElectrical(electrical)
  }

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

    let additionalResult
    if (selectedType() === 'Print') {
      additionalResult = await getApi('check-bldgadditional-printing', applicationNo)
    } else additionalResult = await getApi('check-bldgadditional-reprinting', applicationNo)

    bldgadditional = additionalResult > 0

    const op = await getApiMulti(`get-opdetails-${division}`, applicationNo)

    setLocation(op.result[0])
    setType(op.result2[0])
    setAssessor(op.result3[0])
    setTotalOp(calculateTotal(op.result4))
    setDateOp(dayjs(op.result5[0]).format('MMMM DD, YYYY'))
    setApplicationId(op.result6[0])

    // setAssessorId(op.result12[0])
    // setDescriptionList(op.result8)
    // setAmountList(op.result9)
    // setDateOpList(op.result10)
    // calculateAmounts()

    getPrintDetails(division, op.result6[0])
    getPrintDetailsFees(division, op.result6[0])

    getSignatureImage(employeeId())

    const approversignId = await geteSignId(276)
    getApprovedDate(approversignId, applicationNo)
    // const assessorId = await getEmployeeId(op.result7[0])
    // const assessorsignId = await geteSignId(assessorId)
    getAssessedDate(division, op.result6[0])
  }

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

  const getListForPrinting = async (division: string) => {
    try {
      setIsLoading(true)
      setLoadingText('Downloading Data')
      let response: any
      if (selectedType() === 'Print') response = await getApiMulti(`get-listopprinting-${division}`)
      else response = await getApiMulti(`get-listopreprinting-${division}`)

      if (filter() !== '' && filter().trim().length !== 0) {
        const filteredApplications = response.result.filter((item: string) => item.includes(filter()))
        const filteredIndices = response.result.map((item: string, index: number) => (item.includes(filter()) ? index : -1)).filter((index: number) => index !== -1)
        const filteredNames = filteredIndices.map((index: number) => response.result2[index])

        if (division === 'electrical') {
          setApplicationListElectrical(filteredApplications)
          setNameListElectrical(filteredNames)
        } else if (division === 'occupancy') {
          setApplicationListOccupancy(filteredApplications)
          setNameListOccupancy(filteredNames)
        } else {
          setApplicationListBuilding(filteredApplications)
          setNameListBuilding(filteredNames)
        }
        setIsLoading(false)
        return
      }

      if (division === 'electrical') {
        setApplicationListElectrical(response.result)
        setNameListElectrical(response.result2)
      } else if (division === 'occupancy') {
        setApplicationListOccupancy(response.result)
        setNameListOccupancy(response.result2)
      } else {
        setApplicationListBuilding(response.result)
        setNameListBuilding(response.result2)
      }
      setIsLoading(false)
    } catch (error) {
      console.error(error)
    }
  }

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

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

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

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

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

    setIsLoading(true)
    setLoadingText(`Processing ${application}`)
    if (division === 'electrical') {
      await setNewStatus(division, 'ELECTRICAL ORDER OF PAYMENT PRINTED', '171', 'ELECOPPRINTED', 1)
      await setNewStatus(division, 'ELECTRICAL ORDERPAYMENT RELEASED', '97', 'ELECRELEASED', 1)
      await setNewStatus(division, 'FOR ELECTRICAL OFFICIAL RECEIPT VALIDATION', '98', 'ELECORVALIDATE', 0)
      await updateDocflow(division, application, 'FOR ELECTRICAL ORDER OF PAYMENT PRINTING')
    } else if (division === 'occupancy') {
      await setNewStatus(division, 'OCCUPANCY ORDER OF PAYMENT PRINTED', '173', 'OCCOPPRINTED', 1)
      await setNewStatus(division, 'OCCUPANCY ORDER OF PAYMENT RELEASED', '174', 'OCCOPRELEASED', 1)
      await setNewStatus(division, 'ORDER OF PAYMENT RELEASE FOR BUREAU OF FIRE', '24', 'OCOOPRELEASE', 0)
      await updateDocflow(division, application, 'APPROVED FOR PRINTING OF BUREAU OF FIRE AND ORDER OF PAYMENT')
    }

    updateOrderofpayment = await updateOp(division)

    if (updateOrderofpayment) {
      postTransaction(application)
      setPrintedApplication(application)
      setPrinted(true)

      setLoadingText(`Generating PDF`)
      if (division === 'electrical') {
        createPdfElectrical()
      } else if (division === 'occupancy') {
        createPdfOccupancy()
      } else console.log('building')
    }
    setIsLoading(false)
  }

  const rePrintHandler = async (division: string, application: string) => {
    let popsExist: boolean = false
    let popsPaid: boolean = false

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

    setIsLoading(true)
    setLoadingText(`Reprinting ${application}`)

    if (selectedType().includes('Void')) {
      setLoadingText('Clearing POPS records')

      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
      }

      // const status = await statusPopsOp(application)
      // const message = status.message

      if (!popsExist) {
        setIsLoading(false)
        setVoidError(true)
        setErrorMessage('No record found on Pops')
        return
      }

      if (popsPaid) {
        setIsLoading(false)
        setVoidError(true)
        setErrorMessage('Already Paid')
        return
      }

      setLoadingText('Processing for Re-approval')
      if (division === 'electrical') {
        await setNewStatus(division, 'ELECTRICAL ORDER OF PAYMENT VOIDED', '173', 'ELECOPVOIDED', 1)
        await setNewStatus(division, 'FOR ELECTRICAL ORDER OF PAYMENT APPROVAL', '94', 'ELECOPAPPROVE', 0)
         setLoadingText('Processing for Re-approvalsss222')
        await updateDocflow(division, application, 'FOR ELECTRICAL ORDER OF PAYMENT PRINTING')
        setLoadingText('Processing for Re-approvalsss')
        await updateDocflow(division, application, 'FOR ELECTRICAL OFFICIAL RECEIPT VALIDATION')
        await updateOpForApproval(division, application)
        setLoadingText('Processing for Re-approvalsss')
        await clearEsignTransactions(application)
      } else if (division === 'occupancy') {
        await setNewStatus(division, 'OCCUPANCY ORDER OF PAYMENT VOIDED', '174', 'OCCOPVOIDED', 1)
        //UNFINISH
        await updateDocflow(division, application, 'APPROVED FOR PRINTING OF BUREAU OF FIRE AND ORDER OF PAYMENT')
      }

      const successVoid = await voidPopsOp(application)
      if (successVoid) {
        await postTransaction(application)
      } else {
        setIsLoading(false)
      }
    } else {
      setLoadingText('Generating PDF')
      setPrintedApplication(application)
      setPrinted(true)

      if (division === 'electrical') {
        createPdfElectrical()
      } else if (division === 'occupancy') {
        createPdfOccupancy()
      } else console.log('building')
    }
    setIsLoading(false)
  }

  const updateOp = async (division: string) => {
    const post = await postApi(`update-opprinted-${division}`, {
      data: parseInt(applicationId().toString(), 10),
    })
    return post
  }

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

    const post = await postApi(`post-newstatus-${division}`, {
      data: statusid,
      data2: formattedDate,
      data3: status,
      data4: tag,
      data5: tagword,
      data6: parseInt(approved.toString(), 10),
      data7: parseInt(employeeId().toString(), 10),
    })
    return post
  }

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

  const getSignatureImage = async (id: number) => {
    try {
      const response = await getApi('get-signatureimage', id)
      const image = response
      _signatureAssessor.set(image)

      const response2 = await getApi('get-signatureimage', 276)
      const image2 = response2
      _signatureApprover.set(image2)
      return true
    } catch {
      return false
    }
  }

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

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

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

  const getApprovedDate = async (id: number, application: string) => {
    const response = await getApi('get-signeddate', id, application)
    _approvedDate.set(response)
  }

  const getAssessedDate = async (division: string, id: number) => {
    const response = await getApi(`get-signeddateassessed-${division}`, id)
    _assessedDate.set(response)
  }

  // const getEmployeeId = async (name: string) => {
  //   try {
  //     const response = await ofetch(API + 'get-employeeid/' + name, { parseResponse: JSON.parse })
  //     const result = response.result
  //     return parseInt(result)
  //   } catch (error) {
  //     return 0
  //   }
  // }

  const refresh = async () => {
    if (isBuilding()) await getListForPrinting('building')
    if (isOccupancy()) await getListForPrinting('occupancy')
    if (isElectrical()) await getListForPrinting('electrical')
  }

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

  // const gotoProfile = () => {
  //   sessionStorage.setItem('name', employeeName())
  //   navigate('/profile')
  // }

  const voidPopsOp = async (application: string) => {
    const response = await voidPopsApi(application)
    if (response.includes('Error')) return false
    return true
  }

  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 updateOpForApproval = async (division: string, application: string) => {
    const response = await postApi(`update-opforapproval-${division}`, { data: application })
    return response
  }

  const clearEsignTransactions = async (application: string) => {
    const response = await deleteApi('delete-esigntransactions', { data: application })
    return response
  }

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

    setConfigNotification(true)
  }

  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 getPassword = async () => {
    const response = await getApi('get-password', employeeId())
    setConfigEncPassword(response)
  }

  const updateDisplayName = async () => {
    const response = await getApiMulti('get-employeename', employeeId())
    console.log(response.result)
    sessionStorage.setItem('name', response.result)
    setEmployeeName(response.result)
  }

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

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

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

    if (logged) {
      setSelectedType('Print')

      await checkDivision()
      if (isBuilding()) await getListForPrinting('building')
      if (isOccupancy()) await getListForPrinting('occupancy')
      if (isElectrical()) await getListForPrinting('electrical')
    }
  })

  createEffect(async () => {
    if (filter() !== '') {
      if (isBuilding()) await getListForPrinting('building')
      if (isOccupancy()) await getListForPrinting('occupancy')
      if (isElectrical()) await getListForPrinting('electrical')
    } else if (filter() === '') {
      if (isBuilding()) await getListForPrinting('building')
      if (isOccupancy()) await getListForPrinting('occupancy')
      if (isElectrical()) await getListForPrinting('electrical')
    }
  })

  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="profile">{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">
                  <Show when={isBuilding()}>
                    <Tabs.Trigger class="tabs__trigger" value="building">
                      Building
                    </Tabs.Trigger>
                  </Show>
                  <Show when={isOccupancy()}>
                    <Tabs.Trigger class="tabs__trigger" value="occupancy">
                      Occupancy
                    </Tabs.Trigger>
                  </Show>
                  <Show when={isElectrical()}>
                    <Tabs.Trigger class="tabs__trigger" value="electrical">
                      Electrical
                    </Tabs.Trigger>
                  </Show>
                  <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>
                </Row>

                <Padding top={0} bottom={0} right={10} left={10}>
                  <Row content="split">
                    <Input value={filter()} onChange={setFilter} placeholder="Filter Application Number" />
                    <Row>
                      {/* <Combobox options={listType} value={selectedType()} onChange={setSelectedType} placeholder="Select Type" width='200px' /> */}
                      <Button label="Refresh Data" edges="curved" design="bo-primary" icon={VsRefresh} onClick={refresh}></Button>
                    </Row>
                  </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>
                      {applicationListBuilding().map((item: string, index: number) => (
                        <tr>
                          <td>{item}</td>
                          <td>{nameListBuilding()[index]}</td>

                          <td>
                            <ModalButton
                              class="modal"
                              label="Show Details"
                              design="bo-link"
                              background="#121e2acc"
                              color="#ffffffec"
                              function={async () => {
                                await getopdetails('building', 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">{nameListBuilding()[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().toLocaleString('en-US', {
                                        minimumFractionDigits: 2,
                                      })}
                                    </span>
                                  </section>
                                </Padding>

                                <Row padding="2rem 0 0 0">
                                  <Button wide label="Print" edges="curved" design="bo-primary" onClick={() => printHandler('building', 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="occupancy">
                <Row>
                  <h2>List of Ready to Print in Occupancy Order of Payments</h2>
                </Row>

                <Padding top={0} bottom={0} right={10} left={10}>
                  <Row content="split">
                    <Input value={filter()} onChange={setFilter} placeholder="Filter Application Number" />
                    <Row>
                      {/* <Combobox options={listType} value={selectedType()} onChange={setSelectedType} placeholder="Select Type" width='200px' /> */}
                      <Button label="Refresh Data" edges="curved" design="bo-primary" icon={VsRefresh} onClick={refresh}></Button>
                    </Row>
                  </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().toLocaleString('en-US', {
                                        minimumFractionDigits: 2,
                                      })}
                                    </span>
                                  </section>
                                </Padding>

                                <Row padding="2rem 0 0 0">
                                  <Show when={selectedType() === 'Print'}>
                                    <Button wide label="Print" edges="curved" design="bo-primary" onClick={() => printHandler('occupancy', item)}></Button>
                                  </Show>
                                  <Show when={selectedType() !== 'Print'}>
                                    <Button wide label="Reprint" edges="curved" design="bo-primary" onClick={() => rePrintHandler('occupancy', item)}></Button>
                                  </Show>
                                  <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>
                  <Padding top={2} bottom={2} right={0} left={0}>
                    <h3>Ready for Signing and Printing Electrical Order of Payments</h3>
                  </Padding>
                </Row>

                <Padding top={0} bottom={0} right={9} left={9}>
                  <Row content="split">
                    <Input value={filter()} onChange={setFilter} placeholder="Filter Application Number" />
                    <Row gap={0.5}>
                      {/* <AiOutlineQuestionCircle size={24}/> */}
                      <Combobox options={listType} value={selectedType()} onChange={setSelectedType} placeholder="Select Type" width="250px" />
                      <Button label="Refresh Data" edges="curved" design="bo-primary" icon={VsRefresh} onClick={refresh}></Button>
                    </Row>
                  </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)
                                }}
                              >
                                <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().toLocaleString('en-US', {
                                          minimumFractionDigits: 2,
                                        })}
                                      </span>
                                    </section>
                                  </Padding>

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

      <div onClick={closeNotification}>
        <Modal trigger={printed()} 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">Printed</span>
                </Box>
              </Row>
              <Row padding="2rem 0 0 0">
                <h2>{printedApplication()}</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>

      <div onClick={() => setVoidError(false)}>
        <Modal trigger={voidError()} 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>Invalid Application Void</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>
    </>
  )
}
