/**
 * @format
 */

import {
  Box,
  Button,
  Checkbox,
  CheckboxGroup,
  Flex,
  HStack,
  Text,
  useTheme,
  VStack
} from '@chakra-ui/react'
import React, {FormEvent, useEffect, useState} from 'react'
import DataTable, {
  Direction,
  Alignment,
  PaginationComponentProps
} from 'react-data-table-component'
import {useSearchParams} from 'react-router-dom'
import {KeyValue} from '../types/types'
import '../styles/vantageDataTable.css'

import leftChevron from '../assets/images/icons/leftChevron.svg'
import rightChevron from '../assets/images/icons/rightChevron.svg'
import leftDoubleChevron from '../assets/images/icons/doubleLeftChevron.svg'
import rightDoubleChevron from '../assets/images/icons/rightDoubleChevron.svg'
import {ModalWindow} from './Modal/Modal'

interface DataTableProps {
  data: any
  selectableRows?: boolean
  selectableRowsNoSelectAll?: boolean
  selectableRowsVisibleOnly?: boolean
  selectableRowsHighlight?: boolean
  selectableRowsSingle?: boolean
  expandableRows?: boolean
  expandOnRowClicked?: boolean
  expandOnRowDoubleClicked?: boolean
  expandableRowsHideExpander?: boolean
  pagination?: boolean
  highlightOnHover?: boolean
  striped?: boolean
  pointerOnHover?: boolean
  dense?: boolean
  persistTableHead?: boolean
  noHeader?: boolean
  fixedHeader?: boolean
  fixedHeaderScrollHeight?: string
  progressPending?: boolean
  noTableHead?: boolean
  noContextMenu?: boolean
  direction?: Direction
  subHeader?: boolean
  subHeaderAlign?: Alignment
  subHeaderWrap?: boolean
  responsive?: boolean
  disabled?: boolean
  /**
   * Sets the number of rows to show per page
   * */
  rowsToShowPerPage?: number
  /**
   * CSS styles for all the rows except heading
   * */
  rowStyle?: KeyValue
  /**
   * CSS styles for the heading cells
   * */
  headCellsStyle?: KeyValue
}
export const VantageDataTable = ({
  data,
  selectableRows = false,
  selectableRowsNoSelectAll = false,
  selectableRowsVisibleOnly = false,
  selectableRowsHighlight = false,
  selectableRowsSingle = false,
  expandableRows = false,
  expandOnRowClicked = false,
  expandOnRowDoubleClicked = false,
  expandableRowsHideExpander = false,
  pagination = true,
  highlightOnHover = false,
  striped = false,
  pointerOnHover = false,
  dense = false,
  persistTableHead = false,
  noHeader = false,
  fixedHeader = false,
  fixedHeaderScrollHeight = '200px',
  progressPending = false,
  noTableHead = false,
  noContextMenu = false,
  direction = Direction.LTR,
  subHeaderAlign = Alignment.RIGHT,
  subHeaderWrap = false,
  responsive = false,
  disabled = false,
  rowsToShowPerPage = 10,

  headCellsStyle,

  rowStyle
}: DataTableProps) => {
  const [columns, setColumns] = useState<any>([])
  const [columnsFilter, setColumnsFilter] = useState<any>([])
  const [rowData, setRowData] = useState<any>([])
  const [columnsFilterArr, setColumnsFilterArr] = useState<any>([])
  const theme = useTheme()
  const grey = theme.colors.grey
  const customStyles = {
    rows: {
      style: {
        minHeight: '52px', // override the row height
        backgroundColor: 'white',
        fontSize: '14px',
        color: grey['900'],
        ...rowStyle
      }
    },
    headCells: {
      style: {
        backgroundColor: 'white',
        textTransform: 'uppercase',
        fontWeight: 'bold',
        fontSize: '14px',
        color: grey['500'],
        ...headCellsStyle
      }
    }
  }

  const processRawData = () => {
    const cols: any = []
    const colsFilter: any = {}
    const colsFilterArr: any = []

    if (data.length) {
      Object.keys(data[0]).forEach(key => {
        if (
          (columnsFilter[key] && columnsFilter[key].selected) ||
          !columnsFilter[key]
        ) {
          cols.push({
            name: key,
            selector: (row: any) => row[key],
            sortable: true,
            grow: 2
          })
        }

        console.log(key, searchParams.get(key))

        if (!columnsFilter[key]) {
          colsFilter[key] = {
            name: key,
            selected: searchParams.get(key) === 'false' ? false : true
          }
          colsFilterArr.push(key)
        }
      })
      console.log({columnsFilter})
    }

    setColumns(cols)

    if (Object.keys(columnsFilter).length === 0) {
      setColumnsFilter(colsFilter)
      setColumnsFilterArr(colsFilterArr)
    }

    setRowData(data)
  }

  useEffect(() => {
    processRawData()
  }, [])

  const [searchParams, setSearchParams] = useSearchParams()

  const [page, setPage] = useState<number>(1)
  const [segment, setSegment] = useState<number>(1)
  const [segs, setSegs] = useState<Array<number>>([])
  const [pagesPerSegment, setPagesPerSegment] = useState<number>(5)
  const [totalPages, setTotalPages] = useState<number>(0)
  const [openFilters, setOpenFilters] = useState<boolean>(false)
  const handlePageChange = (pageNumber: number, totalRows: number) => {
    console.log('page changed', pageNumber, totalRows)
  }
  const manageSegment = (curPage: number) => {
    const curSegment = parseInt((curPage / rowsToShowPerPage).toFixed(1), 10)

    if (curSegment === 0) {
      setSegment(1)
    } else {
      setSegment(curSegment)
    }
  }

  const navigateToNextPage = () => {
    const nextPage = page + 1

    if (nextPage <= totalPages) {
      manageSegment(nextPage)
      setPage(nextPage)
    }
  }
  const navigateToPrevPage = () => {
    const nextPage = page - 1

    if (nextPage > 0) {
      manageSegment(nextPage)
      setPage(nextPage)
    }
  }

  const paginationProps = {
    borderWidth: '1px',
    borderColor: 'grey.300',
    minW: '38px !important',
    px: '14px',
    py: '12px',
    ml: '0 !important',
    borderRightRadius: '0',
    bgRepeat: 'no-repeat',
    bgPosition: '50% 50%',
    borderLeftWidth: '0',
    borderRadius: 0
  }
  const buttonBoxProps = {
    w: '14px',
    h: '14px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  }

  useEffect(() => {
    const sgs: Array<number> = []
    for (let s = 0; s < pagesPerSegment; s++) {
      sgs.push(s)
    }
    setSegs(sgs)
  }, [pagesPerSegment])

  const paginationComponent = ({
    rowsPerPage,
    rowCount,
    currentPage
  }: PaginationComponentProps) => {
    const tPages = parseInt((rowCount / rowsPerPage).toFixed(1), 10)
    setTotalPages(tPages)

    if (tPages < pagesPerSegment) {
      setPagesPerSegment(tPages)
    }

    return (
      <>
        {rowData && (
          <Flex justifyContent="flex-end">
            <HStack m="4">
              <Button
                {...paginationProps}
                borderLeftRadius="4px"
                borderLeftWidth={1}
                onClick={() => {
                  manageSegment(1)
                  setPage(1)
                }}
              >
                <Box {...buttonBoxProps}>
                  <img src={leftDoubleChevron} height="14px" />
                </Box>
              </Button>
              <Button
                {...paginationProps}
                onClick={() => {
                  navigateToPrevPage()
                }}
                borderLeftWidth="0"
              >
                <Box {...buttonBoxProps}>
                  <img src={leftChevron} height="14px" />
                </Box>
              </Button>
              {segs.map((i: number) => (
                <Button
                  key={`pagination_${segment + i + performance.now()}`}
                  color={currentPage === segment + i ? 'blue.600' : 'grey.800'}
                  bgColor={
                    currentPage === segment + i ? 'blue.100' : 'grey.100'
                  }
                  onClick={() => {
                    console.log(segment + i)
                    setPage(segment + i)
                  }}
                  {...paginationProps}
                >
                  <Box w="14px" h="14px">
                    {segment + i}
                  </Box>
                </Button>
              ))}
              <Button
                onClick={() => {
                  navigateToNextPage()
                }}
                {...paginationProps}
              >
                <Box {...buttonBoxProps}>
                  <img src={rightChevron} height="14px" />
                </Box>
              </Button>
              <Button
                onClick={() => {
                  manageSegment(totalPages)
                  setPage(totalPages)
                }}
                {...paginationProps}
                borderRightRadius="4px"
              >
                <Box {...buttonBoxProps}>
                  <img src={rightDoubleChevron} height="14px" />
                </Box>
              </Button>
            </HStack>
          </Flex>
        )}
      </>
    )
  }
  const updateCheckBox = (e: FormEvent, ky: string) => {
    const elm = e.target as HTMLInputElement
    setColumnsFilter((prev: any) => ({
      ...prev,
      [ky]: {
        ...columnsFilter[ky],
        selected: elm.checked
      }
    }))
  }
  useEffect(() => {
    processRawData()
    const searchParamVals: any = {}
    columnsFilterArr.forEach((key: string) => {
      searchParamVals[key] = columnsFilter[key].selected
    })
    setSearchParams({...searchParamVals})
    console.log({searchParamVals})
  }, [columnsFilter])

  return (
    <Box>
      <ModalWindow
        onClose={() => {
          console.log('close')
          setOpenFilters(false)
        }}
        isOpen={openFilters}
        title={'Customize Columns'}
        mainContentAlignment={'left'}
        cancelButtonText={'Close'}
        spreadButtons
      >
        <Box w="200px" textAlign={'left'} p="4">
          <CheckboxGroup colorScheme={'blue'}>
            <VStack spacing={2} alignItems="flex-start">
              {columnsFilterArr.map((key: any) => (
                <>
                  <Checkbox
                    key={`${columnsFilter[key].name}_${performance.now()}`}
                    type="checkbox"
                    onChange={e => {
                      updateCheckBox(e, key)
                    }}
                    isChecked={columnsFilter[key].selected}
                  >
                    <Text textTransform={'capitalize'}>
                      {columnsFilter[key].name}
                    </Text>
                  </Checkbox>
                </>
              ))}
            </VStack>
          </CheckboxGroup>
        </Box>
      </ModalWindow>

      <DataTable
        subHeaderComponent={
          <Button
            minW="5px !important"
            px="5px"
            height="10px"
            bgColor="#062472"
            color="white"
            onClick={() => {
              setOpenFilters(!openFilters)
            }}
          >
            +
          </Button>
        }
        columns={columns}
        data={rowData}
        customStyles={customStyles}
        selectableRows={selectableRows}
        selectableRowsNoSelectAll={selectableRowsNoSelectAll}
        selectableRowsVisibleOnly={selectableRowsVisibleOnly}
        selectableRowsHighlight={selectableRowsHighlight}
        selectableRowsSingle={selectableRowsSingle}
        expandableRows={expandableRows}
        expandOnRowClicked={expandOnRowClicked}
        expandOnRowDoubleClicked={expandOnRowDoubleClicked}
        expandableRowsHideExpander={expandableRowsHideExpander}
        pagination={pagination}
        highlightOnHover={highlightOnHover}
        striped={striped}
        pointerOnHover={pointerOnHover}
        dense={dense}
        persistTableHead={persistTableHead}
        noHeader={noHeader}
        fixedHeader={fixedHeader}
        fixedHeaderScrollHeight={fixedHeaderScrollHeight}
        progressPending={progressPending}
        noTableHead={noTableHead}
        noContextMenu={noContextMenu}
        direction={direction}
        subHeader
        subHeaderAlign={subHeaderAlign}
        subHeaderWrap={subHeaderWrap}
        responsive={responsive}
        disabled={disabled}
        paginationComponent={paginationComponent}
        onChangePage={handlePageChange}
        paginationDefaultPage={page}
        paginationPerPage={rowsToShowPerPage}
      />
    </Box>
  )
}
