import './Main.sass'
import { Logo, Link, Page, Row, Padding, ModalButton, Box, Button } 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'

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

export default () => {
  const [updatedList, setUpdatedList] = createSignal<string[]>([])
  const [totalOp, setTotalOp] = createSignal(0)
  const [assessor, setAssessor] = createSignal('')
  const [approver, setApprover] = createSignal('')
  const [dateOp, setDateOp] = createSignal('')

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

  const getListOfReadyForApprovalFiltered = async (list: number[]) => {
    let newList: number[] = []

    for (let i = 0; i < list.length; i++) {
      const response = await ofetch(API + 'get-laststatus-electrical/' + list[i], { parseResponse: JSON.parse })
      if (response.result === 'FOR ELECTRICAL ORDER OF PAYMENT APPROVAL') {
        newList.push(list[i])
      }
    }

    return [...newList]
  }

  const getApplicationById = async (list: number[]) => {
    let applicationList: string[] = []

    for (let i = 0; i < list.length; i++) {
      const response = await ofetch(API + 'get-applicationbyid-electrical/' + list[i], { parseResponse: JSON.parse })
      applicationList.push(response.result)
    }

    setUpdatedList([...applicationList])
  }

  const load = async () => {
    // const listForApproval = await getListForApproval()
    // const listOfReadyForApprovalFiltered = await getListOfReadyForApprovalFiltered(listForApproval)
    // await getApplicationById(listOfReadyForApprovalFiltered)

    // console.log(listOfReadyForApprovalFiltered)
    await getopdetails()
  }

  const getopdetails = async () => {
    const op = await ofetch(API + 'get-opdetails-electrical/23512', { parseResponse: JSON.parse })
    setTotalOp(calculateTotal(op.result4))
    setAssessor(await getEmployeeName(op.result[0]))
    setApprover(await getEmployeeName(op.result2[0]))
    setDateOp(dayjs(op.result5[0]).format('MMMM DD, YYYY'))
  }

  const calculateTotal = (list: number[]) => {
    let total = 0
    for (let i = 0; i < list.length; i++) {
      total += parseInt(list[i].toString())
    }
    return total
  }

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

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

  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">
              <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>
              <Tabs.Content class="tabs__content" value="building">
                <Row>
                  <h2>List of Ready to Approve and Sign Building Order of Payments</h2>
                </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>
              </Tabs.Content>
              <Tabs.Content class="tabs__content" value="electrical">
                <Row>
                  <h2>List of Ready to Approve and Sign Electrical Order of Payments</h2>
                </Row>
                <table class="table">
                  <thead>
                    <tr>
                      <th>Application Number</th>
                      <th>Name</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <td>111</td>
                      <td>11</td>
                      <td>
                        <ModalButton class="modal" label="Show Details" design="bo-link" background="#121e2acc" color="#ffffffec">
                          <Padding top={0} left={2} right={2} bottom={0}>
                            <Box curved thickness={1} padding={1}>
                              <span class="modal__application-number">25-0000000123</span>
                            </Box>
                            <Row>
                              <span class="modal__name">Sample Name</span>
                            </Row>
                            <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">Total Fee:</span>
                              <span class="modal__row__detail">
                                {PESO} {totalOp().toFixed(2)}
                              </span>
                            </section>

                            <Row gap={1} padding="1rem 0 0 0">
                              <Button label="Disapprove" edges="curved" design="bo-danger"></Button>
                              <Button label="Approve" edges="curved" design="bo-primary"></Button>
                            </Row>
                          </Padding>
                        </ModalButton>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </Tabs.Content>
            </Tabs>
          </Row>
        </Padding>
      </Page>
    </>
  )
}
