import React from 'react';
import { components } from 'react-select';

const SUBSCRIPTION_OPTION_VALUES = ['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'recurring_percent'];

/**
 * SubscriptionProOption
 *
 * Renders a react-select option. For subscription-type options, it shows a
 * lock badge and fires the `onSubscriptionClick` callback on mousedown
 * (mousedown fires BEFORE react-select processes the click and closes the menu).
 *
 * The modal itself must be rendered at the parent level (outside the dropdown)
 * to survive the dropdown unmounting.
 *
 * Props passed by react-select: all standard Option props
 * Extra prop via selectProps: onSubscriptionClick (function)
 */
const SubscriptionProOption = (props) => {
    const isSubscriptionOption = SUBSCRIPTION_OPTION_VALUES.includes(props.data.value);

    // Retrieve the callback from selectProps (passed via the <Select> component)
    const onSubscriptionClick = props.selectProps && props.selectProps.onSubscriptionClick;

    const handleMouseDown = (e) => {
        if (isSubscriptionOption && onSubscriptionClick) {
            e.preventDefault();
            e.stopPropagation();
            onSubscriptionClick();
        }
    };

    return (
        <components.Option {...props} innerProps={{ ...props.innerProps, onMouseDown: isSubscriptionOption ? handleMouseDown : props.innerProps.onMouseDown }}>
            {props.data.label}
        </components.Option>
    );
};

export default SubscriptionProOption;