// src/gcodefiles.js

import { useState, useRef } from 'react'

import { Button, Flex, Space, Modal, Dropdown, message } from 'antd'
import ObjectTable from '../common/ObjectTable'
import NewProduct from './Products/NewProduct'

import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'

import useColumnVisibility from '../hooks/useColumnVisibility'

import GridIcon from '../../Icons/GridIcon'
import ListIcon from '../../Icons/ListIcon'
import useViewMode from '../hooks/useViewMode'

import ColumnViewButton from '../common/ColumnViewButton'

const Parts = (filter) => {
  const [messageApi, contextHolder] = message.useMessage()

  const [newProductOpen, setNewProductOpen] = useState(false)
  const tableRef = useRef()
  const [viewMode, setViewMode] = useViewMode('part')
  const [columnVisibility, setColumnVisibility] = useColumnVisibility('part')

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

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Flex justify={'space-between'}>
          <Space size='small'>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ColumnViewButton
              type='part'
              loading={false}
              collapseState={columnVisibility}
              updateCollapseState={setColumnVisibility}
            />
          </Space>
          <Space>
            <Button
              icon={viewMode === 'cards' ? <ListIcon /> : <GridIcon />}
              onClick={() =>
                setViewMode(viewMode === 'cards' ? 'list' : 'cards')
              }
            />
          </Space>
        </Flex>
        <ObjectTable
          ref={tableRef}
          visibleColumns={columnVisibility}
          type='part'
          cards={viewMode === 'cards'}
          filter={filter}
        />
      </Flex>
      <Modal
        open={newProductOpen}
        footer={null}
        width={700}
        onCancel={() => {
          setNewProductOpen(false)
        }}
        destroyOnHidden={true}
      >
        <NewProduct
          onOk={() => {
            setNewProductOpen(false)
            messageApi.success('Product created successfully!')
            tableRef.current?.reload()
          }}
          reset={newProductOpen}
        />
      </Modal>
    </>
  )
}

export default Parts
