import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { memo, useEffect, useState } from 'react';
// import { useDebounce } from 'use-debounce';
import { ArrowLeft, Columns, Delete, Edit, Filters, Refresh } from '@helpdice/icons';
// import InfiniteScroll from 'react-infinite-scroll-component';
import _ from 'lodash';
// import Text from '../text';
import Container from '../grid/grid-container';
import Grid from '../grid';
import Button from '../button';
import Tooltip from '../tooltip';
import Table from './table';
import Popover from '../popover';
// import Input from '../input';
// import Select from '../select';

function DataTable(_ref) {
  var _ref$cols = _ref.cols,
    cols = _ref$cols === void 0 ? [] : _ref$cols,
    _ref$rows = _ref.rows,
    rows = _ref$rows === void 0 ? [] : _ref$rows,
    _ref$readOnly = _ref.readOnly,
    readOnly = _ref$readOnly === void 0 ? false : _ref$readOnly,
    _ref$heading = _ref.heading,
    heading = _ref$heading === void 0 ? [] : _ref$heading,
    _ref$filter = _ref.filter,
    filter = _ref$filter === void 0 ? true : _ref$filter,
    menu = _ref.menu,
    _ref$sideMenu = _ref.sideMenu,
    sideMenu = _ref$sideMenu === void 0 ? false : _ref$sideMenu,
    _ref$style = _ref.style,
    style = _ref$style === void 0 ? {} : _ref$style,
    children = _ref.children,
    _ref$onBack = _ref.onBack,
    onBack = _ref$onBack === void 0 ? function () {
      window.history.back();
    } : _ref$onBack,
    onRefresh = _ref.onRefresh,
    _onFilters = _ref.onFilters,
    onSelectedDelete = _ref.onSelectedDelete,
    onSelectedEdit = _ref.onSelectedEdit,
    onSelected = _ref.onSelected,
    _ref$disableViewColum = _ref.disableViewColumn,
    disableViewColumn = _ref$disableViewColum === void 0 ? false : _ref$disableViewColum,
    _ref$rowDraggable = _ref.rowDraggable,
    rowDraggable = _ref$rowDraggable === void 0 ? false : _ref$rowDraggable,
    onDragOver = _ref.onDragOver,
    onDragEnter = _ref.onDragEnter,
    onDragLeave = _ref.onDragLeave,
    onDrop = _ref.onDrop,
    onRowClick = _ref.onRowClick,
    dataLength = _ref.dataLength,
    viewLength = _ref.viewLength,
    _onPageChange = _ref.onPageChange,
    _ref$disableMenu = _ref.disableMenu,
    disableMenu = _ref$disableMenu === void 0 ? false : _ref$disableMenu,
    _ref$cursorPagination = _ref.cursorPagination,
    cursorPagination = _ref$cursorPagination === void 0 ? false : _ref$cursorPagination,
    previousCursor = _ref.previousCursor,
    nextCursor = _ref.nextCursor,
    _ref$hasMore = _ref.hasMore,
    hasMore = _ref$hasMore === void 0 ? false : _ref$hasMore,
    _ref$stickyHeader = _ref.stickyHeader,
    stickyHeader = _ref$stickyHeader === void 0 ? false : _ref$stickyHeader,
    onNextPage = _ref.onNextPage,
    onPreviousPage = _ref.onPreviousPage;
  var TABLE_ID = _.uniqueId('tbl');
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    hideColumn = _useState2[0],
    setHideColumn = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    openFilter = _useState4[0],
    setOpenFilter = _useState4[1];
  // const [anchorEl, setAnchorEl] = useState(null);
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    selected = _useState6[0],
    setSelected = _useState6[1];

  // const [table_filters] = useDebounce(filters, 500);
  var COLUMNS = cols.filter(function (col) {
    var _String;
    var dataName = (_String = String(col === null || col === void 0 ? void 0 : col.name)) === null || _String === void 0 ? void 0 : _String.replace(' ', '_').toLowerCase();
    return !hideColumn.includes(dataName);
  });

  // State for filter values
  // const [filterValues, setFilterValues] = useState(
  //     COLUMNS.reduce((acc, col) => {
  //         acc[col.filter] = '';
  //         return acc;
  //     }, {})
  // );

  function handleShowFilter() {
    return setOpenFilter(!openFilter);
  }
  useEffect(function () {
    cols.forEach(function (col) {
      var _String2;
      var dataName = (_String2 = String(col === null || col === void 0 ? void 0 : col.name)) === null || _String2 === void 0 ? void 0 : _String2.replace(' ', '_').toLowerCase();
      if (hideColumn.includes(col.name)) {
        document.querySelectorAll("[data-column=\"".concat(dataName, "\"]")).forEach(function (el) {
          el.style.display = 'none !important';
        });
      } else {
        document.querySelectorAll("[data-column=\"".concat(dataName, "\"]")).forEach(function (el) {
          el.style.display = '';
        });
      }
    });
  }, [hideColumn, cols]);
  function handleHideColumnClick(_event, _id) {
    var _String3;
    var id = (_String3 = String(_id)) === null || _String3 === void 0 ? void 0 : _String3.replace(' ', '_').toLowerCase();
    var selectedIndex = hideColumn.indexOf(id);
    var newSelected = [];
    if (selectedIndex === -1) {
      newSelected = newSelected.concat(hideColumn, id);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(hideColumn.slice(1));
    } else if (selectedIndex === hideColumn.length - 1) {
      newSelected = newSelected.concat(hideColumn.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(hideColumn.slice(0, selectedIndex), hideColumn.slice(selectedIndex + 1));
    }
    setHideColumn(newSelected);
  }

  // Children change reset selected
  useEffect(function () {
    setSelected([]);
  }, [children]);

  // const tableHeadStyle = {
  //     position: 'sticky',
  //     // backgroundColor: '#fafafb',
  //     // boxShadow: '0 2px 2px -1px rgba(0, 0, 0, 0.4)',
  //     top: 0,
  //     zIndex: 9,
  //     '& .MuiTableCell-root': {
  //         fontSize: '14px !important',
  //         py: 0.2
  //     }
  //     // ...borderStyle
  // };

  // const borderStyle = {
  //     '& .MuiTableCell-root': {
  //         py: 0.2,
  //         px: 1
  //         // borderLeft: '1px solid #ccc !important',
  //         // borderRight: '1px solid #ccc !important'
  //     },
  //     '& td:first-of-type': {
  //         borderLeft: 'none !important'
  //     },
  //     '& td:last-child': {
  //         borderRight: 'none !important'
  //     }
  //     // '& tr': { borderBottom: '1px solid #ccc !important' }
  // };

  // const handleFilterChange = (name: string, value?: any) => {
  //     setFilterValues({ ...filterValues, [name]: value });
  // };

  // const generateFilterInputs = () => {
  //     return COLUMNS.map((col) => {
  //         const { name: Header, filter: accessor, options } = col;
  //         const filterName = String(col?.name)?.replace(' ', '_').toLowerCase();
  //         // const unq_accessor = _.uniqueId(filterName);
  //         // if (Header === 'actions') {
  //         //   return (
  //         //     <th style={{ margin: '3px' }} data-column={Header} key={unq_accessor}>
  //         //       <Button onClick={applyFilters} auto px={0.6} scale={2 / 3}>Apply</Button>
  //         //     </th>
  //         //   )
  //         // }
  //         return (
  //             <Popover.Item style={{ padding: '3px' }} data-column={Header}>
  //                 {accessor === 'fixed' && (
  //                     <Select
  //                         // key={filterName}
  //                         name={filterName}
  //                         value={filterValues[filterName] ?? 'All'}
  //                         onChange={(newValue) => handleFilterChange(filterName, newValue)}
  //                     >
  //                         <Select.Option value="All">All {Header}</Select.Option>
  //                         {options ? options.map((option: any) => (
  //                             <Select.Option value={option.value}>{option.name}</Select.Option>
  //                         )) : null}
  //                     </Select>
  //                 )}
  //                 {accessor === 'date' && (
  //                     <Input
  //                         // id={`filter-date-${filterName}`}
  //                         // key={filterName}
  //                         htmlType="date"
  //                         name={filterName}
  //                         value={filterValues[filterName]}
  //                         onChange={(e) => handleFilterChange(filterName, e.target.value)}
  //                     />
  //                 )}
  //                 {accessor === 'search' && (
  //                     <Input
  //                         // id={`filter-search-${filterName}`}
  //                         // key={filterName}
  //                         htmlType="text"
  //                         autoComplete="off"
  //                         // ref={filterRefs.current[filterName]} // Dynamically set ref}
  //                         name={filterName}
  //                         style={{ height: 30, minWidth: 160 }}
  //                         value={filterValues[filterName]}
  //                         onChange={(e) => handleFilterChange(filterName, e.target.value)}
  //                         placeholder="Search..."
  //                         fullWidth
  //                     />
  //                 )}
  //             </Popover.Item>
  //         );
  //     });
  // };

  var content = function content() {
    return /*#__PURE__*/React.createElement(React.Fragment, null, cols.map(function (option, _index) {
      var _String4;
      // const colunqid = _.uniqueId(`${option.name}-${index}`);
      var dataName = (_String4 = String(option.name)) === null || _String4 === void 0 ? void 0 : _String4.replace(' ', '_').toLowerCase();
      var isSelected = !hideColumn.includes(dataName);
      return /*#__PURE__*/React.createElement(Popover.Item, {
        selected: isSelected
        // key={colunqid}
        ,
        onClick: function onClick(e) {
          return handleHideColumnClick(e, option.name);
        }
      }, /*#__PURE__*/React.createElement("span", null, option.name));
    }));
  };

  // const filterContent = () => (
  //     <>
  //         {generateFilterInputs()}
  //         <Popover.Item>
  //             <Button onClick={() => {
  //                 if (onFilters) {
  //                     onFilters(filterValues)
  //                 }
  //             }}>Apply</Button></Popover.Item></>
  // )

  return /*#__PURE__*/React.createElement(Container, {
    className: "helpdice-ui-data-table-container",
    direction: "column"
  }, /*#__PURE__*/React.createElement(Grid.Container, {
    style: {
      marginBottom: '0.5rem',
      marginTop: '0.5rem'
    }
  }, heading && /*#__PURE__*/React.createElement(Grid, {
    sm: disableMenu ? 24 : 12,
    xs: 24
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      alignItems: 'center',
      gap: '1rem',
      fontSize: 'larger'
    }
  }, children && /*#__PURE__*/React.createElement(Button, {
    htmlType: "button",
    auto: true,
    scale: 2 / 3,
    px: 0.6,
    iconRight: /*#__PURE__*/React.createElement(ArrowLeft, null),
    onClick: onBack
  }), heading)), !disableMenu && /*#__PURE__*/React.createElement(Grid, {
    sm: 12,
    xs: 24
  }, /*#__PURE__*/React.createElement(Container, {
    width: "100%",
    style: {
      margin: 0,
      gap: '0.6rem'
    },
    justify: "flex-end",
    alignContent: "center"
  }, menu, !children && !readOnly ? /*#__PURE__*/React.createElement(React.Fragment, null, selected.length > 0 && onSelected ? onSelected(selected) : null, onSelectedEdit && selected.length === 1 ? /*#__PURE__*/React.createElement(Tooltip, {
    text: "Edit Selected",
    placement: "bottom",
    font: 0.8,
    px: 0.6,
    py: 0.4,
    type: "dark"
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: function onClick() {
      return onSelectedEdit(selected[0]);
    },
    iconRight: /*#__PURE__*/React.createElement(Edit, null),
    auto: true,
    htmlType: "button",
    scale: 2 / 3,
    px: 0.6
  })) : null, onSelectedDelete && selected.length > 1 ? /*#__PURE__*/React.createElement(Tooltip, {
    text: "Delete Selected",
    placement: "bottom",
    font: 0.8,
    px: 0.6,
    py: 0.4,
    type: "dark"
  }, /*#__PURE__*/React.createElement(Button, {
    onClick: function onClick() {
      return onSelectedDelete(selected);
    },
    auto: true,
    scale: 2 / 3,
    px: 0.6,
    htmlType: "button",
    iconRight: /*#__PURE__*/React.createElement(Delete, null)
  })) : null, onRefresh ? /*#__PURE__*/React.createElement(Tooltip, {
    text: "Refresh",
    placement: "bottom",
    font: 0.8,
    px: 0.6,
    py: 0.4,
    type: "dark"
  }, /*#__PURE__*/React.createElement(Button, {
    htmlType: "button",
    onClick: function onClick() {
      return onRefresh();
    },
    auto: true,
    scale: 2 / 3,
    px: 0.6,
    iconRight: /*#__PURE__*/React.createElement(Refresh, null)
  })) : null, _onFilters && filter ? /*#__PURE__*/React.createElement(Tooltip, {
    text: "Columns",
    placement: "bottomEnd",
    font: 0.8,
    px: 0.6,
    py: 0.4,
    type: "dark"
  }, /*#__PURE__*/React.createElement(Button, {
    htmlType: "button",
    onClick: handleShowFilter,
    auto: true,
    scale: 2 / 3,
    px: 0.6,
    iconRight: /*#__PURE__*/React.createElement(Filters, null)
  })) : null, !disableViewColumn && /*#__PURE__*/React.createElement(Tooltip, {
    text: "Columns",
    placement: "bottomEnd",
    font: 0.8,
    px: 0.6,
    py: 0.4,
    type: "dark"
  }, /*#__PURE__*/React.createElement(Popover, {
    disableItemsAutoClose: true,
    placement: "bottomEnd",
    child: content
  }, /*#__PURE__*/React.createElement(Button, {
    htmlType: "button",
    onClick: function onClick() {},
    auto: true,
    scale: 2 / 3,
    px: 0.6,
    iconRight: /*#__PURE__*/React.createElement(Columns, null)
  })))) : null))), children ? /*#__PURE__*/React.createElement("div", {
    style: {
      padding: '1rem'
    }
  }, children) : /*#__PURE__*/React.createElement("div", {
    style: {
      gap: 5,
      display: 'flex',
      flexDirection: sideMenu ? 'row' : 'column'
    }
  }, sideMenu ? /*#__PURE__*/React.createElement(Container, {
    direction: "column",
    style: {
      width: '15rem',
      gap: 5,
      padding: '0.5rem 0.7rem',
      border: '1px solid #cfcfcf',
      borderRadius: '5px'
    }
  }, sideMenu) : null, /*#__PURE__*/React.createElement("div", {
    onDragOver: onDragOver,
    onDragEnter: onDragEnter,
    onDragLeave: onDragLeave,
    onDrop: onDrop,
    id: TABLE_ID,
    className: "helpdice-ui-table-container",
    style: _extends({
      position: 'relative',
      overflowY: 'auto',
      maxWidth: 'calc(100vw - 1.5rem)',
      width: sideMenu ? 'calc(100vw - 17.2rem)' : 'inherit !important'
    }, style)
  }, /*#__PURE__*/React.createElement(Table, {
    stickyHeader: stickyHeader,
    readOnly: readOnly,
    cursorPagination: cursorPagination,
    previousCursor: previousCursor,
    nextCursor: nextCursor,
    hasMore: hasMore,
    onNextPage: onNextPage,
    onPreviousPage: onPreviousPage,
    dataLength: dataLength,
    viewLength: viewLength,
    onPageChange: function onPageChange(page, start, end) {
      if (_onPageChange) {
        _onPageChange(page, start, end);
      }
    },
    onFilters: function onFilters(filters) {
      if (_onFilters) {
        _onFilters(filters);
      }
    },
    onRow: onRowClick,
    rowDraggable: rowDraggable,
    showFilters: openFilter,
    onSelected: function onSelected(selected) {
      return setSelected(selected);
    },
    data: rows,
    style: {
      borderCollapse: 'collapse',
      overflow: 'auto'
    }
  }, COLUMNS.map(function (column) {
    return /*#__PURE__*/React.createElement(Table.Column, {
      style: column === null || column === void 0 ? void 0 : column.style,
      options: column === null || column === void 0 ? void 0 : column.options,
      fontSize: column === null || column === void 0 ? void 0 : column.fontSize,
      prop: column.id,
      label: column.name,
      filter: column === null || column === void 0 ? void 0 : column.filter,
      noWrap: column === null || column === void 0 ? void 0 : column.noWrap,
      align: column === null || column === void 0 ? void 0 : column.align
    });
  })))));
}
export default /*#__PURE__*/memo(DataTable);