import './Assessor.sass'
import { Logo, Page, Row, Padding, ModalButton, Button, Clickable, Link, Modal, Column, Box, Input } from '../../components'
import { FiLogOut } from 'solid-icons/fi'
import { Tabs } from '@kobalte/core/tabs'
import { ofetch } from 'ofetch'
import { onMount, createSignal, Show, createEffect } from 'solid-js'
import dayjs from 'dayjs'
import { checkConnection, createPdf } from '../../utils/functions'
import { FaSolidThumbsUp } from 'solid-icons/fa'
import { _employeeName, _employeeId } from '../../stores/employee'
import { useNavigate } from '@solidjs/router'
import { _applicationNo, _date, _optn, _name, _location, _type, _assessor, _feeList, _codeList, _amountList, _signatureAssessor, _signatureApprover, _assessorid, _approvedDate, _assessedDate } from '../../stores/pdfinfo'
import { VsRefresh } from 'solid-icons/vs'

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

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

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

  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 checkAccess = async (access: string) => {
    try {
      const response = await ofetch(`${API}check-access/${access}/${employeeId()}`)
      const result = response.result
      if (result > 0) return true
      else return false
    } catch {
      return false
    }
  }

  const getPrintDetails = async (id: number) => {
    const response = await ofetch(API + 'get-printdetails-electrical/' + 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

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

  const getPrintDetailsFees = async (id: number) => {
    const response = await ofetch(API + 'get-printdetailsfees-electrical/' + id)
    const feeList = response.result
    const accountCodeList = response.result2
    const amountList = response.result3

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

  // 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()
    await getListForPrinting()
  }

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

    getPrintDetails(op.result11[0])
    getPrintDetailsFees(op.result11[0])
    getSignatureImage(employeeId())

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

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

  const getListForPrinting = async () => {
    try {
      const response = await ofetch(API + 'get-listopprinting-electrical', { parseResponse: JSON.parse })

      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])
        setApplicationList(filteredApplications)
        setNameList(filteredNames)
        return
      }
      setApplicationList(response.result)
      setNameList(response.result2)
    } 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!))
    setEmployeeName(nameStore!)

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

  const printHandler = 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 PRINTED', '171', 'ELECOPPRINTED', 1)
    if (!signed) return

    forprinting = await setNewStatus('FOR ELECTRICAL OFFICIAL RECEIPT VALIDATION', '98', 'ELECORVALIDATE', 0)
    if (!forprinting) return

    updateOrderofpayment = await updateOp()

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

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

  const setNewStatus = async (status: string, tag: string, tagword: string, approved: number) => {
    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(approved.toString()), data7: parseInt(employeeId().toString()) },
      })
      return true
    } catch {
      return false
    }
  }

  const getSignatureImage = async (id: number) => {
    try {
      const response = await ofetch(API + 'get-signatureimage/' + id, { parseResponse: JSON.parse })
      const image = response.result
      _signatureAssessor.set(image)

      const response2 = await ofetch(API + 'get-signatureimage/' + 276, { parseResponse: JSON.parse })
      const image2 = response2.result
      _signatureApprover.set(image2)
      return true
    } catch {
      return false
    }
  }

  const geteSignId = async (id: number) => {
    try {
      const response = await ofetch(API + 'get-esignid/' + id, { parseResponse: JSON.parse })
      const result = response.result
      return result
    } catch {
      return 0
    }
  }

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

    await ofetch(API + 'post-esigntransaction', {
      method: 'POST',
      body: { data: parseInt(id), data2: application, data3: formatedDate },
    })
  }

  const getApprovedDate = async (id: number, application: string) => {
    try {
      const response = await ofetch(API + `get-signeddate/${id}/${application}`, { parseResponse: JSON.parse })
      const result = response.result
      _approvedDate.set(result)
    } catch (error) {
      _approvedDate.set('')
    }
  }

  const getAssessedDate = async (electricalid: number) => {
    try {
      const response = await ofetch(API + 'get-signeddateassessed-electrical/' + electricalid, { parseResponse: JSON.parse })
      const result = response.result
      console.log('date', result)
      _assessedDate.set(result)
    } catch (error) {
      _assessedDate.set('')
    }
  }

  // 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 () => {
    await getListForPrinting()
  }

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

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

    if (logged) {
      await checkDivision()
      await getListForPrinting()
    }
  })

  createEffect(async () => {
    if (filter() !== '') {
      await getListForPrinting()
    } else if (filter() === '') {
      await getListForPrinting()
    }
  })

  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}>
              <Box curved thickness={0} padding="1.25rem 2.25rem" background="#0f131d56">
                <span class="name">{employeeName()}</span>
              </Box>
              <Clickable onClick={logout}>
                <Row gap={0.5}>
                  <FiLogOut size={25} />
                  <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> */}
                  <Box curved thickness={0} background="#602a2abf" padding="1rem 2rem">
                    <h2>Under Development</h2>
                  </Box>
                </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> */}
                  <Box curved thickness={0} background="#602a2abf" padding="1rem 2rem">
                    <h2>Under Development</h2>
                  </Box>
                </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>
                  <Clickable onClick={() => createPdf()}>
                    <h2>List of Ready to Print in Electrical Order of Payments</h2>
                  </Clickable>
                </Row>

                <Padding top={0} bottom={0} right={10} left={10}>
                  <Row content="split">
                    <Input value={filter()} onChange={setFilter} placeholder="Filter Application Number" />
                    <Button label="Refresh Data" edges="curved" design="bo-primary" icon={VsRefresh} onClick={refresh}></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>
                      {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="Print" edges="curved" design="bo-primary" onClick={() => printHandler(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={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>
    </>
  )
}
