import React, { useEffect, useMemo, useRef, useState } from 'react'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import { Card, CardBody, CardHeader, CardTitle, Col, Label, Row } from 'reactstrap'
import collect from 'collect.js'
import { Toast } from 'primereact/toast'
import 'primereact/resources/themes/bootstrap4-light-blue/theme.css'
import 'primeflex/primeflex.css'
import { MantineReactTable } from 'mantine-react-table'
import jquery from 'jquery'
import { isObjEmpty, titleCase } from '../../kytp/util'
import { useSelector } from 'react-redux'
const date = new Date()

const Kanwil = () => {
  const base_url = '/engineN/'
  const toast = useRef(null)

  const refChart1 = useRef()
  const refChart2 = useRef()
  const refChart3 = useRef()
  //   const refChart4 = useRef()

  const [data, setData] = useState([])

  const [urutKanwil, setUrutKanwil] = useState({ categories: [], dataSeries: [] })
  const [urutKpp, setUrutKpp] = useState({ categories: [], dataSeries: [] })
  const [urutSeksi, setUrutSeksi] = useState({ categories: [], dataSeries: [] })
  const [urutPegawai, setUrutPegawai] = useState({ categories: [], dataSeries: [] })
  const storeKpdl = useSelector((state) => state.kpdl)

  useEffect(() => {
    // if (isObjEmpty(paramSelected)) {
    //   return
    // }
    // const kanwil = collect(kanwilSelected).pluck('value').all()
    // const kpp = collect(kppSelected).pluck('value').all()
    const data = storeKpdl.dataUrut

    setUrutKanwil(() => {
      const categories = []
      const dataSeries = []
      data.urutKanwil.map((val, idx) => {
        categories.push(String(val.LABEL).replace('Kanwil DJP', ''))
        dataSeries.push(val.RATA_RATA)
      })
      return { categories, dataSeries }
    })
    setUrutKpp(() => {
      const categories = []
      const dataSeries = []
      data.urutKpp.map((val, idx) => {
        categories.push(String(val.LABEL).replace('KPP Pratama', ''))
        dataSeries.push(val.RATA_RATA)
      })
      return { categories, dataSeries }
    })
    setUrutSeksi(() => {
      const categories = []
      const dataSeries = []
      data.urutSeksi.map((val, idx) => {
        categories.push(String(val.LABEL).replace('Seksi', '') + '-' + String(val.NAMA_KANTOR).replace('KPP Pratama', ''))
        dataSeries.push(val.RATA_RATA)
      })
      return { categories, dataSeries }
    })
    setUrutPegawai(() => {
      const categories = []
      const dataSeries = []
      data.urutPegawai.map((val, idx) => {
        categories.push(String(val.LABEL) + ' - ' + String(val.NAMA_UNIT_ES4).replace('Seksi', '') + ' - ' + String(val.NAMA_KANTOR).replace('KPP Pratama', ''))
        dataSeries.push(val.JUMLAH)
      })
      return { categories, dataSeries }
    })
  }, [storeKpdl.dataMonitoring, storeKpdl.dataUrut])

  const columns = useMemo(
    () => [
      {
        accessorKey: 'LABEL',
        header: 'Unit/Pegawai',
        size: 200,
        mantineTableBodyCellProps: ({ cell }) => {
          const rowObject = cell.row.original
          if (!cell.row.getCanExpand()) {
            if (rowObject.ISEXIST_INWAS === 'FALSE') {
              return { style: { color: 'red' } }
            }
            if (rowObject.NAMA_JABATAN === 'Kepala Seksi') {
              return { style: { color: 'blue' } }
            }
          }
        }
      },
      {
        accessorKey: 'JUMLAH',
        header: 'Jml. Subjek',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID')
      },
      {
        accessorKey: 'JUMLAH_AR',
        header: 'AR Existing',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID')
      },
      {
        accessorKey: 'RATA_RATA',
        header: 'Rata-rata Per AR',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID', { maximumFractionDigits: 2 }),
        sortDescFirst: true
      }
    ],
    []
  )

  const optionsChart = (props, title, urutChart) => {
    return {
      chart: {
        type: 'bar',
        height: 350,
        borderColor: '#EBBA95',
        borderWidth: 2
      },
      title: {
        text: `${title}`,
        style: { fontSize: '14px' },
        useHTML: true
      },

      xAxis: {
        categories: props.categories,
        labels: {
          formatter: function () {
            return urutChart === 4 ? String(this.value).split('-')[0] : this.value
          },
          allowOverlap: false,
          style: {
            whiteSpace: 'wrap',
            overflow: 'allow'
          }
        }
      },
      yAxis: {
        min: 0,
        title: {
          text: null
        },
        labels: {
          overflow: 'justify'
        },
        gridLineWidth: 0
      },
      tooltip: {
        valueSuffix: ' Subjek',
        backgroundColor: '#FCFFC5',
        // pointFormat: '{point.y}',
        formatter: function () {
          return '<b>' + this.x + '</b> : <b>' + Number(this.y).toLocaleString('id-ID', { maximumFractionDigits: 2 }) + '</b>'
        },
        enabled: true
      },
      plotOptions: {
        bar: {
          borderRadius: '20%',
          dataLabels: {
            enabled: true,
            formatter: function () {
              return `${Number(this.y).toLocaleString('id-ID', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2
              })}`
            }
          },
          groupPadding: 0.1
        }
      },
      credits: {
        enabled: false
      },
      series: [{ name: 'Subjek KPDL', data: props.dataSeries }]
    }
  }
  return (
    <>
      <Row style={{ minHeight: '200px' }}>
        <Col md="8">
          <MantineReactTable
            initialState={{ sorting: [{ id: 'RATA_RATA', desc: true }] }}
            columns={columns}
            data={storeKpdl.dataMonitoring}
            enableExpanding
            enableExpandAll //default
            mantineTopToolbarProps={{ className: 'z-0', allowFullScreen: false }}
            enableFullScreenToggle={false}
            enablePagination={false}
            mantineTableBodyCellProps={({ cell }) => ({
              className: 'text-xs py-1',
              sx: {
                backgroundColor: cell.row.depth === 1 || !cell.row.getCanExpand() ? 'ButtonHighlight' : 'inherit',
                fontWeight: cell.row.depth === 0 ? '600' : 'inherit'
              }
            })}
            mantineTableBodyProps={{ className: 'mb-3' }}
            mantineTableHeadCellProps={{ align: 'center', className: 'text-xs p-1' }}
            enableTableFooter
            renderBottomToolbar={
              <div>
                <Row className="pl-5 text-xs">
                  <Col>
                    <Label>Legenda Tabel :</Label>
                    <ul>
                      <li style={{ color: 'blue' }}>Kepala Seksi</li>
                      <li style={{ color: 'red' }}>Eks Kepala/Anggota Seksi terkait</li>
                    </ul>
                  </Col>
                </Row>
              </div>
            }
            mantineTableProps={{
              highlightOnHover: false,
              withColumnBorders: true
            }}
            content
          />
        </Col>
        <Col md="4">
          <Row>
            {urutKanwil.dataSeries.length ? (
              <Col md="12" className="m-1">
                <HighchartsReact ref={refChart1} highcharts={Highcharts} options={optionsChart(urutKanwil, 'Urut Rata-rata Kanwil', 1)} />
              </Col>
            ) : null}
            {urutKpp.dataSeries.length ? (
              <Col md="12" className="m-1">
                <HighchartsReact ref={refChart2} highcharts={Highcharts} options={optionsChart(urutKpp, 'Urut Rata-rata KPP', 2)} />
              </Col>
            ) : null}
            {urutKpp.dataSeries.length ? (
              <Col md="12" className="m-1">
                <HighchartsReact ref={refChart3} highcharts={Highcharts} options={optionsChart(urutSeksi, 'Urut Rata-rata Seksi', 3)} />
              </Col>
            ) : null}
            {urutKpp.dataSeries.length ? (
              <Col md="12" className="m-1">
                <HighchartsReact ref={refChart3} highcharts={Highcharts} options={optionsChart(urutPegawai, 'Jml. Subjek Urut AR', 4)} />
              </Col>
            ) : null}
          </Row>
        </Col>
      </Row>
    </>
  )
}

export default Kanwil