// src/gcodefiles.js

import React, { useState, useRef } from 'react'
import { Button, Flex, Space, Modal, Dropdown, message } from 'antd'
import NewGCodeFile from './GCodeFiles/NewGCodeFile'
import useColumnVisibility from '../hooks/useColumnVisibility'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
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 GCodeFiles = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const [newGCodeFileOpen, setNewGCodeFileOpen] = useState(false)
  const tableRef = useRef()
  const [viewMode, setViewMode] = useViewMode('gcodeFile')

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

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

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Flex justify={'space-between'}>
          <Space>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ColumnViewButton
              type='gcodeFile'
              disabled={false}
              visibleState={columnVisibility}
              updateVisibleState={setColumnVisibility}
            />
          </Space>
          <Space>
            <Button
              icon={viewMode === 'cards' ? <ListIcon /> : <GridIcon />}
              onClick={() =>
                setViewMode(viewMode === 'cards' ? 'list' : 'cards')
              }
            />
          </Space>
        </Flex>
        <ObjectTable
          ref={tableRef}
          type='gcodeFile'
          cards={viewMode === 'cards'}
          visibleColumns={columnVisibility}
        />
      </Flex>
      <Modal
        open={newGCodeFileOpen}
        footer={null}
        width={700}
        onCancel={() => {
          setNewGCodeFileOpen(false)
        }}
        destroyOnHidden={true}
      >
        <NewGCodeFile
          onOk={() => {
            setNewGCodeFileOpen(false)
            messageApi.success('Finished uploading GCode file!')
            tableRef.current?.reload()
          }}
          reset={newGCodeFileOpen}
        />
      </Modal>
    </>
  )
}

export default GCodeFiles
