// src/filamentStocks.js

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

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

import NewFilamentStock from './FilamentStocks/NewFilamentStock'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import useColumnVisibility from '../hooks/useColumnVisibility'
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 FilamentStocks = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const tableRef = useRef()

  const [newFilamentStockOpen, setNewFilamentStockOpen] = useState(false)

  const [viewMode, setViewMode] = useViewMode('filamentStocks')

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

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

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Flex justify={'space-between'}>
          <Space size='small'>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ColumnViewButton
              type='filamentStock'
              loading={false}
              visibleState={columnVisibility}
              updateVisibleState={setColumnVisibility}
            />
          </Space>
          <Space>
            <Button
              icon={viewMode === 'cards' ? <ListIcon /> : <GridIcon />}
              onClick={() =>
                setViewMode(viewMode === 'cards' ? 'list' : 'cards')
              }
            />
          </Space>
        </Flex>

        <ObjectTable
          ref={tableRef}
          visibleColumns={columnVisibility}
          type='filamentStock'
          cards={viewMode === 'cards'}
        />
      </Flex>
      <Modal
        open={newFilamentStockOpen}
        styles={{ content: { paddingBottom: '24px' } }}
        footer={null}
        width={800}
        onCancel={() => {
          setNewFilamentStockOpen(false)
        }}
        destroyOnHidden={true}
      >
        <NewFilamentStock
          onOk={() => {
            setNewFilamentStockOpen(false)
            messageApi.success('New filament stock created successfully.')
            tableRef.current?.reload()
          }}
          reset={newFilamentStockOpen}
        />
      </Modal>
    </>
  )
}

export default FilamentStocks
