// src/Jobs.js

import React, { useState, useRef } from 'react'
import { Button, Flex, Space, Modal, Dropdown, message } from 'antd'
import NewJob from './Jobs/NewJob.jsx'
import useColumnVisibility from '../hooks/useColumnVisibility.js'
import PlusIcon from '../../Icons/PlusIcon.jsx'
import ReloadIcon from '../../Icons/ReloadIcon.jsx'
import ObjectTable from '../common/ObjectTable.jsx'
import ListIcon from '../../Icons/ListIcon.jsx'
import GridIcon from '../../Icons/GridIcon.jsx'
import useViewMode from '../hooks/useViewMode.js'
import ColumnViewButton from '../common/ColumnViewButton.jsx'

const Jobs = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const [newJobOpen, setNewJobOpen] = useState(false)
  const tableRef = useRef()
  const [viewMode, setViewMode] = useViewMode('job')

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

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

  const showNewJobModal = () => {
    setNewJobOpen(true)
  }

  return (
    <>
      <Flex vertical={'true'} gap='large' style={{ height: '100%' }}>
        {contextHolder}
        <Flex justify={'space-between'}>
          <Space size='small'>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ColumnViewButton
              type='job'
              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={'job'}
          visibleColumns={columnVisibility}
          cards={viewMode === 'cards'}
        />
      </Flex>
      <Modal
        open={newJobOpen}
        footer={null}
        width={700}
        onCancel={() => {
          setNewJobOpen(false)
        }}
      >
        <NewJob
          onOk={() => {
            setNewJobOpen(false)
            messageApi.success('New print job created successfully.')
            tableRef.current?.reload()
          }}
          reset={newJobOpen}
        />
      </Modal>
    </>
  )
}

export default Jobs
