// src/gcodefiles.js

import React, { useState, useContext, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Button,
  Flex,
  Space,
  Modal,
  Dropdown,
  Typography,
  Checkbox,
  Popover,
  Input,
  message
} from 'antd'
import { DownloadOutlined } from '@ant-design/icons'

import { AuthContext } from '../context/AuthContext'
import IdDisplay from '../common/IdDisplay'
import ObjectTable from '../common/ObjectTable'
import NewProduct from './Products/NewProduct'
import PartIcon from '../../Icons/PartIcon'
import InfoCircleIcon from '../../Icons/InfoCircleIcon'
import PlusIcon from '../../Icons/PlusIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import XMarkIcon from '../../Icons/XMarkIcon'
import CheckIcon from '../../Icons/CheckIcon'
import useColumnVisibility from '../hooks/useColumnVisibility'
import TimeDisplay from '../common/TimeDisplay'
import GridIcon from '../../Icons/GridIcon'
import ListIcon from '../../Icons/ListIcon'
import useViewMode from '../hooks/useViewMode'

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

const { Text } = Typography

const Parts = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const navigate = useNavigate()
  const [newProductOpen, setNewProductOpen] = useState(false)
  const tableRef = useRef()
  const { authenticated } = useContext(AuthContext)
  const [viewMode, setViewMode] = useViewMode('Parts')

  // Column definitions
  const columns = [
    {
      title: <PartIcon />,
      key: 'icon',
      width: 40,
      fixed: 'left',
      render: () => <PartIcon />
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      fixed: 'left',
      render: (text) => <Text ellipsis>{text}</Text>,
      filterDropdown: ({
        setSelectedKeys,
        selectedKeys,
        confirm,
        clearFilters
      }) =>
        getFilterDropdown({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          propertyName: 'name'
        }),
      onFilter: (value, record) =>
        record.name.toLowerCase().includes(value.toLowerCase())
    },
    {
      title: 'ID',
      dataIndex: '_id',
      key: 'id',
      width: 180,
      render: (text) => <IdDisplay id={text} type={'part'} longId={false} />
    },
    {
      title: 'Product Name',
      key: 'productName',
      width: 200,
      render: (record) => <Text>{record?.product?.name}</Text>,
      filterDropdown: ({
        setSelectedKeys,
        selectedKeys,
        confirm,
        clearFilters
      }) =>
        getFilterDropdown({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          propertyName: 'product name'
        }),
      onFilter: (value, record) =>
        record.product.name.toLowerCase().includes(value.toLowerCase())
    },
    {
      title: 'Product ID',
      key: 'productId',
      width: 180,
      render: (record) => (
        <IdDisplay
          id={record?.product?._id}
          type={'product'}
          longId={false}
          showHyperlink={true}
        />
      )
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt) => {
        if (createdAt) {
          return <TimeDisplay dateTime={createdAt} />
        } else {
          return 'n/a'
        }
      },
      sorter: true
    },
    {
      title: 'Updated At',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (updatedAt) => {
        if (updatedAt) {
          return <TimeDisplay dateTime={updatedAt} />
        } else {
          return 'n/a'
        }
      },
      sorter: true
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right',
      width: 150,
      render: (record) => {
        return (
          <Space gap='small'>
            <Button
              icon={<InfoCircleIcon />}
              onClick={() =>
                navigate(
                  `/dashboard/management/parts/info?partId=${record._id}`
                )
              }
            />
            <Dropdown menu={getPartActionItems(record._id)}>
              <Button>Actions</Button>
            </Dropdown>
          </Space>
        )
      }
    }
  ]

  const [columnVisibility, updateColumnVisibility] = useColumnVisibility(
    'Parts',
    columns
  )

  const getPartActionItems = (id) => {
    return {
      items: [
        {
          label: 'Info',
          key: 'info',
          icon: <InfoCircleIcon />
        },
        {
          label: 'Download',
          key: 'download',
          icon: <DownloadOutlined />
        }
      ],
      onClick: ({ key }) => {
        if (key === 'info') {
          navigate(`/dashboard/management/parts/info?partId=${id}`)
        }
      }
    }
  }

  const getFilterDropdown = ({
    setSelectedKeys,
    selectedKeys,
    confirm,
    clearFilters,
    propertyName
  }) => {
    return (
      <div style={{ padding: 8 }}>
        <Space.Compact>
          <Input
            placeholder={'Search ' + propertyName}
            value={selectedKeys[0]}
            onChange={(e) =>
              setSelectedKeys(e.target.value ? [e.target.value] : [])
            }
            onPressEnter={() => confirm()}
            style={{ width: 200, display: 'block' }}
          />
          <Button
            onClick={() => {
              clearFilters()
              confirm()
            }}
            icon={<XMarkIcon />}
          />
          <Button
            type='primary'
            onClick={() => confirm()}
            icon={<CheckIcon />}
          />
        </Space.Compact>
      </div>
    )
  }

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

  const getViewDropdownItems = () => {
    const columnItems = columns
      .filter((col) => col.key && col.title !== '')
      .map((col) => (
        <Checkbox
          checked={columnVisibility[col.key]}
          key={col.key}
          onChange={(e) => {
            updateColumnVisibility(col.key, e.target.checked)
          }}
        >
          {col.title}
        </Checkbox>
      ))

    return (
      <Flex vertical>
        <Flex vertical gap='middle' style={{ margin: '4px 8px' }}>
          {columnItems}
        </Flex>
      </Flex>
    )
  }

  const visibleColumns = columns.filter(
    (col) => !col.key || columnVisibility[col.key]
  )

  return (
    <>
      <Flex vertical={'true'} gap='large'>
        {contextHolder}
        <Flex justify={'space-between'}>
          <Space size='small'>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <Popover
              content={getViewDropdownItems()}
              placement='bottomLeft'
              arrow={false}
            >
              <Button>View</Button>
            </Popover>
          </Space>
          <Space>
            <Button
              icon={viewMode === 'cards' ? <ListIcon /> : <GridIcon />}
              onClick={() =>
                setViewMode(viewMode === 'cards' ? 'list' : 'cards')
              }
            />
          </Space>
        </Flex>
        <ObjectTable
          ref={tableRef}
          columns={visibleColumns}
          url={`${config.backendUrl}/parts`}
          authenticated={authenticated}
          cards={viewMode === 'cards'}
        />
      </Flex>
      <Modal
        open={newProductOpen}
        footer={null}
        width={700}
        onCancel={() => {
          setNewProductOpen(false)
        }}
        destroyOnHidden={true}
      >
        <NewProduct
          onOk={() => {
            setNewProductOpen(false)
            messageApi.success('Product created successfully!')
            tableRef.current?.reload()
          }}
          reset={newProductOpen}
        />
      </Modal>
    </>
  )
}

export default Parts
