import { useState, useContext, useRef, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Flex, Space, message, Dropdown, Typography } from 'antd'

import { AuthContext } from '../context/AuthContext'
import { PrintServerContext } from '../context/PrintServerContext'

import IdDisplay from '../common/IdDisplay'
import StockAuditIcon from '../../Icons/StockAuditIcon'
import InfoCircleIcon from '../../Icons/InfoCircleIcon'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import TimeDisplay from '../common/TimeDisplay'
import ObjectTable from '../common/ObjectTable'

import config from '../../../config'

const { Text } = Typography

const StockAudits = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const navigate = useNavigate()
  const { printServer } = useContext(PrintServerContext)
  const [initialized, setInitialized] = useState(false)
  const tableRef = useRef()

  const { authenticated } = useContext(AuthContext)

  useEffect(() => {
    if (printServer && !initialized) {
      setInitialized(true)
      printServer.on('notify_stockaudit_update', (updateData) => {
        if (tableRef.current) {
          tableRef.current.updateData(updateData._id, updateData)
        }
      })
    }

    return () => {
      if (printServer && initialized) {
        printServer.off('notify_stockaudit_update')
      }
    }
  }, [printServer, initialized])

  const getStockAuditActionItems = (id) => {
    return {
      items: [
        {
          label: 'Info',
          key: 'info',
          icon: <InfoCircleIcon />
        }
      ],
      onClick: ({ key }) => {
        if (key === 'info') {
          navigate(`/dashboard/inventory/stockaudits/info?stockAuditId=${id}`)
        }
      }
    }
  }

  const columns = [
    {
      title: '',
      dataIndex: '',
      key: 'icon',
      width: 40,
      fixed: 'left',
      render: () => <StockAuditIcon />
    },
    {
      title: 'ID',
      dataIndex: '_id',
      key: 'id',
      width: 180,
      render: (text) => (
        <IdDisplay id={text} type={'stockaudit'} longId={false} />
      )
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => <Text>{status}</Text>
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt) => {
        if (createdAt) {
          return <TimeDisplay dateTime={createdAt} />
        }
        return 'n/a'
      }
    },
    {
      title: 'Updated At',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (updatedAt) => {
        if (updatedAt) {
          return <TimeDisplay dateTime={updatedAt} />
        }
        return 'n/a'
      }
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right',
      width: 150,
      render: (text, record) => {
        return (
          <Space gap='small'>
            <Button
              icon={<InfoCircleIcon />}
              onClick={() =>
                navigate(
                  `/dashboard/inventory/stockaudits/info?stockAuditId=${record._id}`
                )
              }
            />
            <Dropdown menu={getStockAuditActionItems(record._id)}>
              <Button>Actions</Button>
            </Dropdown>
          </Space>
        )
      }
    }
  ]

  const actionItems = {
    items: [
      {
        label: 'New Stock Audit',
        key: 'newStockAudit',
        icon: <PlusIcon />
      },
      { type: 'divider' },
      {
        label: 'Reload List',
        key: 'reloadList',
        icon: <ReloadIcon />
      }
    ],
    onClick: ({ key }) => {
      if (key === 'reloadList') {
        tableRef.current?.reload()
      } else if (key === 'newStockAudit') {
        // TODO: Implement new stock audit creation
        messageApi.info('New stock audit creation not implemented yet')
      }
    }
  }

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Space>
          <Dropdown menu={actionItems}>
            <Button>Actions</Button>
          </Dropdown>
        </Space>
        <ObjectTable
          ref={tableRef}
          columns={columns}
          url={`${config.backendUrl}/stockaudits`}
          authenticated={authenticated}
        />
      </Flex>
    </>
  )
}

export default StockAudits
