// src/gcodefiles.js

import React, { useState, useContext, useRef } from 'react'

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

import { AuthContext } from '../context/AuthContext'

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 = () => {
  const [messageApi, contextHolder] = message.useMessage()

  const [newProductOpen, setNewProductOpen] = useState(false)
  const tableRef = useRef()
  const { authenticated } = useContext(AuthContext)
  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'
          authenticated={authenticated}
          cards={viewMode === 'cards'}
        />
      </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
