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.dataUrutPerubahanPerilakuPenambahanWpBayar

    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.dataMonitoringPerubahanPerilakuPenambahanWpBayar, storeKpdl.dataUrutPerubahanPerilakuPenambahanWpBayar])

  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' } }
          //   }
          // }
        },
        footer: `Total`
      },
      {
        accessorKey: 'BLN_1',
        header: 'Jan',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_1, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_2',
        header: 'Feb',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_2, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_3',
        header: 'Mar',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_3, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_4',
        header: 'Apr',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_4, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_5',
        header: 'Mei',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_5, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_6',
        header: 'Jun',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_6, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_7',
        header: 'Jul',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_7, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_8',
        header: 'Agu',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_8, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_9',
        header: 'Sep',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_9, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_10',
        header: 'Okt',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_10, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_11',
        header: 'Nov',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_11, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'BLN_12',
        header: 'Des',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.BLN_12, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      },
      {
        accessorKey: 'TOTAL',
        header: 'Total',
        size: 80,
        mantineTableBodyCellProps: {
          align: 'right'
        },
        Cell: ({ cell }) => Number(cell.getValue()).toLocaleString('id-ID'),
        footer: (
          <span className="pe-1 right">
            {Number(storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar.reduce((acc, row) => acc + row.TOTAL, 0)).toLocaleString('id-ID', {
              maximumFractionDigits: 0
            })}
          </span>
        )
      }
    ],
    []
  )

  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="12">
          <MantineReactTable
            initialState={{ sorting: [{ id: 'TOTAL', desc: true }] }}
            columns={columns}
            data={storeKpdl.dataMonitoringPerubahanPerilakuPenambahanWpBayar}
            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
            // }}
            mantineTableProps={{
              highlightOnHover: false,
              withColumnBorders: true,
              // withBorder: colorScheme === 'light',
              sx: {
                'tbody > tr > td': {
                  padding: '0.4rem 0.4rem',
                  fontSize: '0.96rem'
                },
                'tfoot > tr > th': {
                  // padding: '1rem 0.4rem',
                  textAlign: 'end',
                  borderBottom: '1px solid #dee2e6',
                  borderRight: '0.0625rem solid #dee2e6',
                  borderTop: 'none',
                  padding: '0.4rem 0.4rem'
                  //   fontSize: "2.96rem"
                }
              }
            }}
            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