import type { OptionProps } from '@blueprintjs/core'
import { Button, HTMLSelect } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { isEqual } from 'lodash'
import { memo, type FC } from 'react'
import { CLOSING_BRACKET, NOT, OPENING_BRACKET, OPERATORS } from '../utils'

const expressionBlock = css`
  display: flex;
  align-items: start;
  position: relative;
  padding-top: 0.5rem;
`

const simpleLabel = css`
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0.4rem 1rem 0.4rem 0.5rem;
`

const cancelButton = css`
  position: absolute;
  top: 0;
  right: -0.5rem;
`

interface ExpressionBlockProps {
  variables: OptionProps[]
  block: OptionProps
  onRemove: () => void
  onModify: (block: OptionProps) => void
}

const ExpressionBlock: FC<ExpressionBlockProps> = ({
  variables,
  block,
  onRemove,
  onModify,
}) => (
  <div className={expressionBlock}>
    {variables.find(value => isEqual(value, block)) && (
      <HTMLSelect
        minimal
        options={variables}
        value={block.value}
        onChange={event => {
          const selectedOption = event.currentTarget.selectedOptions[0]
          onModify({
            value: Number(selectedOption.value),
            label: selectedOption.label,
          })
        }}
        iconName='caret-down'
      />
    )}
    {OPERATORS.find(value => isEqual(value, block)) && (
      <HTMLSelect
        minimal
        options={OPERATORS}
        value={block.value}
        onChange={event => {
          const selectedOption = event.currentTarget.selectedOptions[0]
          onModify({
            value: selectedOption.value,
            label: selectedOption.label,
          })
        }}
        iconName='caret-down'
      />
    )}
    {(isEqual(block, NOT) ||
      isEqual(block, OPENING_BRACKET) ||
      isEqual(block, CLOSING_BRACKET)) && (
      <span className={simpleLabel}>{block.label}</span>
    )}
    <Button
      small
      onClick={onRemove}
      icon='cross'
      minimal
      className={cancelButton}
    />
  </div>
)

export default memo(ExpressionBlock)
