// src/stockAudits.js

import { useState, useRef } from 'react'

import { Button, Flex, Space, Modal, Dropdown } from 'antd'

import NewStockAudit from './StockAudits/NewStockAudit'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import useColumnVisibility from '../hooks/useColumnVisibility'
import ObjectTable from '../common/ObjectTable'
import ListIcon from '../../Icons/ListIcon'
import GridIcon from '../../Icons/GridIcon'
import useViewMode from '../hooks/useViewMode'
import ColumnViewButton from '../common/ColumnViewButton'

const StockAudits = () => {
  const tableRef = useRef()

  const [newStockAuditOpen, setNewStockAuditOpen] = useState(false)

  const [viewMode, setViewMode] = useViewMode('stockAudits')

  const [columnVisibility, setColumnVisibility] =
    useColumnVisibility('stockAudits')

  const actionItems = {
    items: [
      {
        label: 'New Stock audit',
        key: 'newStockAudit',
        icon: <PlusIcon />
      },
      { type: 'divider' },
      {
        label: 'Reload List',
        key: 'reloadList',
        icon: <ReloadIcon />
      }
    ],
    onClick: ({ key }) => {
      if (key === 'reloadList') {
        tableRef.current?.reload()
      } else if (key === 'newStockAudit') {
        setNewStockAuditOpen(true)
      }
    }
  }

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        <Flex justify={'space-between'}>
          <Space size='small'>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ColumnViewButton
              type='stockAudit'
              loading={false}
              visibleState={columnVisibility}
              updateVisibleState={setColumnVisibility}
            />
          </Space>
          <Space>
            <Button
              icon={viewMode === 'cards' ? <ListIcon /> : <GridIcon />}
              onClick={() =>
                setViewMode(viewMode === 'cards' ? 'list' : 'cards')
              }
            />
          </Space>
        </Flex>

        <ObjectTable
          ref={tableRef}
          visibleColumns={columnVisibility}
          type='stockAudit'
          cards={viewMode === 'cards'}
        />
      </Flex>
      <Modal
        open={newStockAuditOpen}
        styles={{ content: { paddingBottom: '24px' } }}
        footer={null}
        width={800}
        onCancel={() => {
          setNewStockAuditOpen(false)
        }}
        destroyOnHidden={true}
      >
        <NewStockAudit
          onOk={() => {
            setNewStockAuditOpen(false)
            tableRef.current?.reload()
          }}
          reset={newStockAuditOpen}
        />
      </Modal>
    </>
  )
}

export default StockAudits
