// src/gcodefiles.js

import { useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Button,
  Flex,
  Space,
  Modal,
  Dropdown,
  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 ObjectTableViewButton from '../common/ObjectTableViewButton'
import FilterSidebarButton from '../common/FilterSidebarButton'
import SortSidebarButton from '../common/SortSidebarButton'
import useViewMode from '../hooks/useViewMode'
import useFilterSidebarVisibility from '../hooks/useFilterSidebarVisibility'
import useSortSidebarVisibility from '../hooks/useSortSidebarVisibility'
import ExportListButton from '../common/ExportListButton'

const Products = () => {
  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(
    'product',
    columns
  )

  const [showFilterSidebar, setShowFilterSidebar] =
    useFilterSidebarVisibility('Products')

  const [showSortSidebar, setShowSortSidebar] =
    useSortSidebarVisibility('Products')

  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' className='h-100'>
        <Flex justify={'space-between'} style={{ minHeight: 0 }}>
          <Space size='small'>
            <Dropdown menu={actionItems}>
              <Button>Actions</Button>
            </Dropdown>
            <ExportListButton objectType='product' />
            <Popover
              content={getViewDropdownItems()}
              placement='bottomLeft'
              arrow={false}
            >
              <Button>View</Button>
            </Popover>
          </Space>
          <Space>
            <SortSidebarButton
              active={showSortSidebar}
              onClick={() => setShowSortSidebar(!showSortSidebar)}
            />
            <FilterSidebarButton
              active={showFilterSidebar}
              onClick={() => setShowFilterSidebar(!showFilterSidebar)}
            />
            <ObjectTableViewButton
              viewMode={viewMode}
              setViewMode={setViewMode}
              showEndingDivider={true}
            />
          </Space>
        </Flex>
        <ObjectTable
          ref={tableRef}
          type={'product'}
          cards={viewMode === 'cards'}
          showFilterSidebar={showFilterSidebar}
          showSortSidebar={showSortSidebar}
          expandHeight={true}
          saveFilterInSession={true}
          saveFilterInUrl={true}
          useFilterInSession={true}
          useFilterInUrl={true}
          saveSortInSession={true}
          saveSortInUrl={true}
          useSortInSession={true}
          useSortInUrl={true}
        />
      </Flex>
      <Modal
        open={newProductOpen}
        footer={null}
        width={700}
        onCancel={() => {
          setNewProductOpen(false)
        }}
        destroyOnHidden={true}
      >
        <NewProduct
          onOk={() => {
            setNewProductOpen(false)
            tableRef.current?.reload()
          }}
          reset={newProductOpen}
        />
      </Modal>
    </>
  )
}

export default Products
