import './Main.sass'
import { Logo, Link, Page, Row, Padding, ModalButton, Box, Button, Modal, Column } from '../../components/'
import { FiLogOut } from 'solid-icons/fi'
import { Tabs } from '@kobalte/core/tabs'
import { ofetch } from 'ofetch'
import { onMount, createSignal } from 'solid-js'
import dayjs from 'dayjs'
import { checkConnection, createPdf } from '../../utils/functions'
import { FaSolidThumbsUp } from 'solid-icons/fa'
// @ts-ignore
// import * as openssl from 'openssl-nodejs'

const API = import.meta.env.VITE_BACKEND
const PESO = import.meta.env.VITE_PESO
const ID = import.meta.env.VITE_HEADID

export default () => {
  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 [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 [applicationList, setApplicationList] = createSignal<string[]>([])
  const [nameList, setNameList] = createSignal<string[]>([])

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

  const getListForApproval = async () => {
    try {
      const response = await ofetch(API + 'get-listopapproval-electrical', { parseResponse: JSON.parse })
      setApplicationList(response.result)
      setNameList(response.result2)
    } catch (error) {
      console.error(error)
    }
  }

  const load = async () => {
    setConnected(await checkConnection())
    if (connected() === false) {
      setErrorMessage('Could not gather list of applicaitons')
      return
    }

    await getListForApproval()
  }

  const getopdetails = async (applicationNo: string) => {
    const op = await ofetch(API + 'get-opdetails-electrical/' + applicationNo, { parseResponse: JSON.parse })
    setAssessor(op.result7[0])
    setLocation(op.result5[0])
    setType(op.result6[0])
    setDateOp(dayjs(op.result10[0]).format('MMMM DD, YYYY'))
    setApplicationId(op.result11[0])
    setAssessorId(op.result12[0])
    setTotalOp(calculateTotal(op.result9))

    setDescriptionList(op.result8)
    setAmountList(op.result9)
    setDateOpList(op.result10)
    calculateAmounts()
  }

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

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

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

    signed = await setNewStatus('ELECTRICAL ORDER OF PAYMENT APPROVED AND SIGNED', '170', 'ELECOPAPPROVEDSIGNED')
    if (!signed) return

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

    updateOrderofpayment = await updateOp()

    if (updateOrderofpayment) {
      setApprovedApplication(application)
      setApproved(true)
    }
  }

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

    try {
      await ofetch(API + 'post-newstatus-electrical', {
        method: 'POST',
        body: { data: statusid, data2: formattedDate, data3: status, data4: tag, data5: tagword, data6: parseInt(ID) },
      })
      return true
    } catch {
      return false
    }
  }

  const updateOp = async () => {
    try {
      await ofetch(API + 'update-op-electrical', {
        method: 'POST',
        body: { data: parseInt(applicationId().toString()) },
      })
      return true
    } catch {
      return false
    }
  }

  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()
  }

  const openPDF = () => {
    createPdf()
  }

  onMount(async () => {
    await load()
  })

  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}>
              <span class="name">Login Name</span>
              <Link to="/">
                <FiLogOut size={25} />
              </Link>
            </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>
                </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 Occupancy Order of Payments</h2>
                </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="electrical">
                <Row>
                  <h2 onClick={openPDF}>List of Ready to Approve and Sign Electrical Order of Payments</h2>
                </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>
                      {applicationList().map((item, index) => (
                        <tr>
                          <td>{item}</td>
                          <td>{nameList()[index]}</td>

                          <td>
                            <ModalButton
                              class="modal"
                              label="Show Details"
                              design="bo-link"
                              background="#121e2acc"
                              color="#ffffffec"
                              function={async () => {
                                await getopdetails(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">{nameList()[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().toFixed(2)}
                                    </span>
                                  </section>
                                </Padding>

                                <Row padding="2rem 0 0 0">
                                  <Button wide label="Approve" edges="curved" design="bo-primary" onClick={() => approveHandler(item)}></Button>
                                  <span class="modal__cancel">Click anywhere to cancel</span>
                                </Row>
                              </Padding>
                            </ModalButton>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </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>
    </>
  )
}
