import { useMemo } from 'react'
import { Card, Select, Button, Flex, Dropdown } from 'antd'
import PropTypes from 'prop-types'
import {
  getModelByName,
  getModelProperties
} from '../../../database/ObjectModels'
import BinIcon from '../../Icons/BinIcon'

const DIRECTION_OPTIONS = [
  { label: 'Ascending', value: 'ascend' },
  { label: 'Descending', value: 'descend' }
]

const SortSidebar = ({
  type,
  sorter = {},
  onSortChange,
  stretchHeight = false
}) => {
  const model = getModelByName(type)
  const modelProps = getModelProperties(type)

  const propertyOptions = useMemo(() => {
    if (!model.sorters) return []
    return model.sorters
      .map((name) => modelProps.find((p) => p.name === name))
      .filter(Boolean)
      .map((prop) => ({
        label: prop.label,
        value: prop.name
      }))
  }, [model.sorters, modelProps])

  const menuItems = {
    items: [
      {
        key: 'clearSort',
        label: 'Clear sort',
        danger: true,
        icon: <BinIcon />,
        onClick: () => onSortChange({})
      }
    ]
  }

  const changeProperty = (field) => {
    if (!field) {
      onSortChange({})
      return
    }
    onSortChange({
      field,
      order: sorter.order || 'ascend'
    })
  }

  const changeDirection = (order) => {
    if (!sorter.field) return
    onSortChange({ field: sorter.field, order })
  }

  return (
    <Card style={{ flexShrink: 0, height: stretchHeight ? '100%' : undefined }}>
      <Flex vertical gap='middle'>
        <Flex justify='space-between'>
          <Dropdown menu={menuItems} trigger={['hover']} placement='bottomLeft'>
            <Button type='default'>Actions</Button>
          </Dropdown>
        </Flex>
        <Select
          placeholder='Property'
          value={sorter.field || undefined}
          onChange={changeProperty}
          options={propertyOptions}
          style={{ minWidth: 80, flex: 1 }}
          allowClear
        />
        <Select
          placeholder='Direction'
          value={sorter.order || undefined}
          onChange={changeDirection}
          options={DIRECTION_OPTIONS}
          style={{ minWidth: 80, flex: 1 }}
          disabled={!sorter.field}
          allowClear={false}
        />
      </Flex>
    </Card>
  )
}

SortSidebar.propTypes = {
  type: PropTypes.string.isRequired,
  sorter: PropTypes.object,
  onSortChange: PropTypes.func.isRequired,
  stretchHeight: PropTypes.bool
}

export default SortSidebar
