import { Col, Dropdown, Menu, Row } from 'antd'
import classNames from 'classnames'
import React from 'react'
import { useCallback, useMemo } from 'react'
import { Icon } from '../Icon'
import { Text, Paragraph } from '../Typography'
import { ShopifyStore } from 'redux/Shopify/types'
import './index.scss'

type CommonStore = Pick<ShopifyStore, 'name'>

interface FilterProps {
  className?: string
  items?: CommonStore[]
  disabled?: boolean
  value?: CommonStore
  onConnectToAnotherStore: () => void
  onChange?: (item: CommonStore) => void
}

const Filter: React.FC<FilterProps> = ({
  items = [],
  onChange,
  className,
  value,
  disabled = false,
  onConnectToAnotherStore
}) => {
  const handleClickItem = useCallback(
    (item: CommonStore) => () => {
      onChange?.(item)
    },
    []
  )

  const menu = useMemo(() => {
    return (
      <Menu className="shopify-store-selection__item">
        {items.map((item, index) => (
          <Menu.Item onClick={handleClickItem(item)} key={index}>
            <Text preset="medium16">{item.name}</Text>
          </Menu.Item>
        ))}
        <Menu.Item onClick={onConnectToAnotherStore}>
          <Text preset="medium16" className="text--blue">
            Connect another Shopify Store
          </Text>
        </Menu.Item>
      </Menu>
    )
  }, [items])

  return (
    <Dropdown
      className={classNames(
        'shopify-store-selection m__t--8',
        className,
        disabled ? 'cursor-not-allowed' : 'cursor-pointer'
      )}
      overlay={menu}
      trigger={['click']}
      disabled={disabled}
    >
      <Row
        align="middle"
        className="p__y--8 p__x--14 border-box bo__radius--8 cursor-pointer"
        justify="space-between"
        wrap={false}
      >
        <Col className="filter__label" flex={1}>
          <Paragraph
            ellipsis={{ rows: 1 }}
            preset="semibold16"
            className="m__r--10"
          >
            {value?.name || items?.[0]?.name}
          </Paragraph>
        </Col>
        <Icon name="arrow-down" />
      </Row>
    </Dropdown>
  )
}

export default Filter
