import React, { FunctionComponent, useState } from 'react';
import { StyleSheet, Text, TextStyle } from 'react-native';
import { Menu, MenuItem } from 'react-native-material-menu';
import Icon from 'react-native-vector-icons/Ionicons';

export interface IDropDownMenuStyleProps {
    menuIcon?: any;
    menuText?: TextStyle;
}

interface IDropDownMenuProps {
    menuItems: string[];
    onSelectItem?: (item: string) => void;
    renderCustomItem?: (item: string) => React.ReactElement;
    style?: IDropDownMenuStyleProps
}

export const DropDownMenu: FunctionComponent<IDropDownMenuProps> = ({
    menuItems,
    style,
    onSelectItem,
    renderCustomItem
}) => {
    const [visible, setVisible] = useState<boolean>(false);
    const mergedStyle = { ...defaultStyle, ...style };

    const hideMenu = () => setVisible(false);
    const showMenu = () => setVisible(true);
    const onMenuItemPressed = (selectedItem: string) => () => {
        if (onSelectItem) {
            onSelectItem(selectedItem);
        }
        hideMenu();
    }

    const renderMenuItems = (itemOptions: string[]) => {
        const menusArray = itemOptions.map((item: string) => {
            return (
                <MenuItem onPress={onMenuItemPressed(item)} key={item}>
                    {renderCustomItem ? renderCustomItem(item) : <Text style={mergedStyle.menuText}>{item}</Text>}
                </MenuItem>
            );
        });
        return menusArray;
    }

    return (
        <Menu
            visible={visible}
            anchor={<Icon name="ellipsis-vertical-sharp" style={mergedStyle.menuIcon} onPress={showMenu} />}
            onRequestClose={hideMenu}
        >
            {renderMenuItems(menuItems)}
        </Menu>

    );
};

const defaultStyle = StyleSheet.create({
    menuIcon: { color: '#0086CF', fontSize: 30 }
});
