// src/hosts.js

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

import NewHost from './Hosts/NewHost'

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 Hosts = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const [newHostOpen, setNewHostOpen] = useState(false)
  const tableRef = useRef()

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

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

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

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

        <Modal
          open={newHostOpen}
          footer={null}
          width={700}
          onCancel={() => {
            setNewHostOpen(false)
          }}
        >
          <NewHost
            onOk={() => {
              setNewHostOpen(false)
              messageApi.success('New host added successfully.')
              tableRef.current?.reload()
            }}
            reset={newHostOpen}
          />
        </Modal>
      </Flex>
    </>
  )
}

export default Hosts
