// src/gcodefiles.js

import React, { useEffect, useState, useContext, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import moment from 'moment'

import { Table, Button, Flex, Space, Modal, Dropdown, message } from 'antd'
import { createStyles } from 'antd-style'
import {
  LoadingOutlined,
  PlusOutlined,
  DownloadOutlined,
  ReloadOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'

import { AuthContext } from '../../Auth/AuthContext'

import IdText from '../common/IdText'
import NewProduct from './Products/NewProduct'
import ProductIcon from '../../Icons/ProductIcon'

const useStyle = createStyles(({ css, token }) => {
  const { antCls } = token
  return {
    customTable: css`
      ${antCls}-table {
        ${antCls}-table-container {
          ${antCls}-table-body,
          ${antCls}-table-content {
            scrollbar-width: thin;
            scrollbar-color: #eaeaea transparent;
            scrollbar-gutter: stable;
          }
        }
      }
    `
  }
})

const Products = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const navigate = useNavigate()
  const { styles } = useStyle()

  const [productsData, setProductsData] = useState([])

  const [newProductOpen, setNewProductOpen] = useState(false)

  const [loading, setLoading] = useState(true)

  const { authenticated } = useContext(AuthContext)

  const fetchProductsData = useCallback(async () => {
    try {
      const response = await axios.get('http://localhost:8080/products', {
        params: {
          page: 1,
          limit: 25
        },
        headers: {
          Accept: 'application/json'
        },
        withCredentials: true // Important for including cookies
      })
      setProductsData(response.data)
      setLoading(false)
      //setPagination({ ...pagination, total: response.data.totalItems }); // Update total count
    } catch (error) {
      if (error.response) {
        messageApi.error(
          'Error updating printer details:',
          error.response.status
        )
      } else {
        messageApi.error(
          'An unexpected error occurred. Please try again later.'
        )
      }
    }
  }, [messageApi])

  useEffect(() => {
    if (authenticated) {
      fetchProductsData()
    }
  }, [authenticated, fetchProductsData])

  const getProductActionItems = (id) => {
    return {
      items: [
        {
          label: 'Info',
          key: 'info',
          icon: <InfoCircleOutlined />
        },
        {
          label: 'Download',
          key: 'download',
          icon: <DownloadOutlined />
        }
      ],
      onClick: ({ key }) => {
        if (key === 'info') {
          navigate(`/management/products/info?productId=${id}`)
        }
      }
    }
  }

  // Column definitions
  const columns = [
    {
      title: '',
      dataIndex: '',
      key: '',
      width: 40,
      fixed: 'left',
      render: () => <ProductIcon></ProductIcon>
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      fixed: 'left'
    },
    {
      title: 'ID',
      dataIndex: '_id',
      key: 'id',
      fixed: 'left',
      width: 165,
      render: (text) => <IdText id={text} type={'product'} longId={false} />
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt) => {
        if (createdAt) {
          const formattedDate = moment(createdAt).format('YYYY-MM-DD HH:mm:ss')
          return <span>{formattedDate}</span>
        } else {
          return 'n/a'
        }
      }
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right',
      width: 150,
      render: (text, record) => {
        return (
          <Space gap='small'>
            <Button
              icon={<InfoCircleOutlined />}
              onClick={() =>
                navigate(`/management/products/info?productId=${record._id}`)
              }
            />
            <Dropdown menu={getProductActionItems(record._id)}>
              <Button>Actions</Button>
            </Dropdown>
          </Space>
        )
      }
    }
  ]

  const actionItems = {
    items: [
      {
        label: 'New Product',
        key: 'newProduct',
        icon: <PlusOutlined />
      },
      { type: 'divider' },
      {
        label: 'Reload List',
        key: 'reloadList',
        icon: <ReloadOutlined />
      }
    ],
    onClick: ({ key }) => {
      if (key === 'reloadList') {
        fetchProductsData()
      } else if (key === 'newProduct') {
        setNewProductOpen(true)
      }
    }
  }

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Space>
          <Dropdown menu={actionItems}>
            <Button>Actions</Button>
          </Dropdown>
        </Space>
        <Table
          dataSource={productsData}
          columns={columns}
          className={styles.customTable}
          pagination={false}
          scroll={{ y: 'calc(100vh - 270px)' }}
          rowKey='_id'
          loading={{ spinning: loading, indicator: <LoadingOutlined spin /> }}
        />
      </Flex>
      <Modal
        open={newProductOpen}
        footer={null}
        width={700}
        onCancel={() => {
          setNewProductOpen(false)
        }}
        destroyOnClose
      >
        <NewProduct
          onOk={() => {
            setNewProductOpen(false)
            fetchProductsData()
          }}
          reset={newProductOpen}
        />
      </Modal>
    </>
  )
}

export default Products
