// src/filaments.js

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

import NewFilament from './Filaments/NewFilament'

import useColumnVisibility from '../hooks/useColumnVisibility'
import ColumnViewButton from '../common/ColumnViewButton'
import ObjectTable from '../common/ObjectTable'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import ListIcon from '../../Icons/ListIcon'
import GridIcon from '../../Icons/GridIcon'
import useViewMode from '../hooks/useViewMode'

const Filaments = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const [newFilamentOpen, setNewFilamentOpen] = useState(false)
  const tableRef = useRef()

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

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

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

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

        <Modal
          open={newFilamentOpen}
          footer={null}
          width={700}
          onCancel={() => {
            setNewFilamentOpen(false)
          }}
        >
          <NewFilament
            onOk={() => {
              setNewFilamentOpen(false)
              messageApi.success('New filament added successfully.')
              tableRef.current?.reload()
            }}
            reset={newFilamentOpen}
          />
        </Modal>
      </Flex>
    </>
  )
}

export default Filaments
