// src/gcodefiles.js

import { useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Button,
  Flex,
  Space,
  Modal,
  Dropdown,
  message,
  Tag,
  Checkbox,
  Popover,
  Input
} from 'antd'
import { DownloadOutlined } from '@ant-design/icons'
import IdDisplay from '../common/IdDisplay'
import TimeDisplay from '../common/TimeDisplay'
import ObjectTable from '../common/ObjectTable'
import NewProduct from './Products/NewProduct'
import ProductIcon from '../../Icons/ProductIcon'
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 GridIcon from '../../Icons/GridIcon'
import ListIcon from '../../Icons/ListIcon'
import useViewMode from '../hooks/useViewMode'

const Products = () => {
  const [messageApi, contextHolder] = message.useMessage()
  const navigate = useNavigate()
  const [newProductOpen, setNewProductOpen] = useState(false)
  const tableRef = useRef()

  const [viewMode, setViewMode] = useViewMode('Products')

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

  // Column definitions
  const columns = [
    {
      title: <ProductIcon />,
      key: 'icon',
      width: 40,
      fixed: 'left',
      render: () => <ProductIcon />
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      fixed: 'left',
      filterDropdown: ({
        setSelectedKeys,
        selectedKeys,
        confirm,
        clearFilters
      }) =>
        getFilterDropdown({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          propertyName: 'name'
        }),
      onFilter: (value, record) =>
        record.name.toLowerCase().includes(value.toLowerCase()),
      sorter: true
    },
    {
      title: 'ID',
      dataIndex: '_id',
      key: 'id',
      fixed: 'left',
      width: 180,
      render: (text) => <IdDisplay id={text} type={'product'} longId={false} />,
      filterDropdown: ({
        setSelectedKeys,
        selectedKeys,
        confirm,
        clearFilters
      }) =>
        getFilterDropdown({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          propertyName: 'ID'
        }),
      onFilter: (value, record) =>
        record?._id.toLowerCase().includes(value.toLowerCase()),
      sorter: true
    },
    {
      title: 'Tags',
      dataIndex: 'tags',
      key: 'tags',
      width: 170,
      render: (tags) => {
        if (!tags || !Array.isArray(tags)) return 'n/a'
        if (tags.length == 0) return 'n/a'
        return (
          <Space size={[0, 8]} wrap>
            {tags.map((tag, index) => (
              <Tag key={index} color='blue'>
                {tag}
              </Tag>
            ))}
          </Space>
        )
      },
      filterDropdown: ({
        setSelectedKeys,
        selectedKeys,
        confirm,
        clearFilters
      }) =>
        getFilterDropdown({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          propertyName: 'tags'
        }),
      onFilter: (value, record) =>
        record.tags?.some((tag) =>
          tag.toLowerCase().includes(value.toLowerCase())
        ),
      sorter: true
    },
    {
      title: 'Version',
      dataIndex: 'version',
      key: 'version',
      width: 120,
      render: (text) => (text ? <Tag>{text}</Tag> : 'n/a'),
      filterDropdown: ({
        setSelectedKeys,
        selectedKeys,
        confirm,
        clearFilters
      }) =>
        getFilterDropdown({
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          propertyName: 'version'
        }),
      onFilter: (value, record) =>
        record.version?.toLowerCase().includes(value.toLowerCase()),
      sorter: true
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt) => {
        if (createdAt) {
          return <TimeDisplay dateTime={createdAt} />
        } else {
          return 'n/a'
        }
      },
      sorter: true,
      defaultSortOrder: 'descend'
    },
    {
      title: 'Updated At',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (updatedAt) => {
        if (updatedAt) {
          return <TimeDisplay dateTime={updatedAt} />
        } else {
          return 'n/a'
        }
      },
      sorter: true,
      defaultSortOrder: 'descend'
    },
    {
      title: 'Actions',
      key: 'actions',
      fixed: 'right',
      width: 150,
      render: (record) => {
        return (
          <Space gap='small'>
            <Button
              icon={<InfoCircleIcon />}
              onClick={() =>
                navigate(
                  `/dashboard/management/products/info?productId=${record._id}`
                )
              }
            />
            <Dropdown menu={getProductActionItems(record._id)}>
              <Button>Actions</Button>
            </Dropdown>
          </Space>
        )
      }
    }
  ]

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

  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 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 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>
    )
  }

  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}
          type={'product'}
          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 Products
