// src/Printers.js

import { useState, useRef } from 'react'
import { Button, message, Dropdown, Space, Flex, Modal } from 'antd'
import NewPrinter from './Printers/NewPrinter'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import ObjectTable from '../common/ObjectTable'
import ColumnViewButton from '../common/ColumnViewButton'

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

const Printers = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const [newPrinterOpen, setNewPrinterOpen] = useState(false)
  const tableRef = useRef()

  // View mode state (cards/list), persisted in sessionStorage via custom hook
  const [viewMode, setViewMode] = useViewMode('Printers')

  // Column visibility state, persisted in sessionStorage via custom hook
  const [columnVisibility, setColumnVisibility] = useColumnVisibility('printer')

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

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Flex justify={'space-between'}>
          <Space>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ColumnViewButton
              type='printer'
              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='printer'
          cards={viewMode === 'cards'}
          visibleColumns={columnVisibility}
        />

        <Modal
          open={newPrinterOpen}
          footer={null}
          width={700}
          onCancel={() => {
            setNewPrinterOpen(false)
          }}
          destroyOnHidden
        >
          <NewPrinter
            onOk={() => {
              setNewPrinterOpen(false)
              messageApi.success('New printer added successfully.')
              tableRef.current?.reload()
            }}
            reset={newPrinterOpen}
          />
        </Modal>
      </Flex>
    </>
  )
}

export default Printers
