import React from 'react';
import _ from 'lodash';
import {
	StyleSheet,
	View,
	TouchableOpacity,
} from 'react-native';
import {
	Text,
	color,
	NixplayIcon as Icon,
} from 'nixplay-ui-kit';
import PropTypes from 'prop-types';

import { debounceWrapper } from '~/lib/utils';
import * as TEST_IDS from '~/store/testIDConstants';
import setTestID from '~/test/testUtils';
import { color as basicColor } from '~/styles/variables';

const styles = StyleSheet.create({
	container: {
		flex: 1,
		flexDirection: 'row',
	},
	button: {
		flex: 1,
		flexDirection: 'row',
		borderStyle: 'solid',
		borderWidth: 1,
		borderTopRightRadius: 4,
		borderTopLeftRadius: 4,
		borderBottomRightRadius: 4,
		borderBottomLeftRadius: 4,
		borderColor: color.borderMistBlue,
		padding: 2,
		alignItems: 'center',
		height: 42,
	},
	textContainer: {
		flex: 1,
		flexDirection: 'column',
		justifyContent: 'center',
		padding: 6,
	},
});

export const CustomPicker = (props) => {
	const {
		action, itemSelected, name, placeholder, hasError,
	} = props;
	const TouchableOpacityEx = debounceWrapper(TouchableOpacity);
	const displayText = (!_.isEmpty(itemSelected)) ? itemSelected : placeholder;
	const txtColor = (!_.isEmpty(itemSelected)) ? basicColor.wrikeGreen2 : basicColor.gitlabGray4;
	const errorColor = (hasError) ? color.red : color.borderMistBlue;
	return (
		<View style={styles.container}>
			<TouchableOpacityEx
				onPress={() => action()}
				style={[styles.button, { borderColor: errorColor }]}
				{...setTestID(`${TEST_IDS.NIX_PICKER}${name}`)}
			>
				<View style={styles.textContainer}>
					<Text
						textStyle="body"
						color={txtColor}
						numberOfLines={1}
						ellipsizeMode="tail"
					>{displayText}
					</Text>
				</View>
				<Icon name="arrow-down-thick-small" testID="ArrowDown" color={txtColor} style={{ marginRight: 6 }} />
			</TouchableOpacityEx>
		</View>
	);
};

CustomPicker.propTypes = {
	action: PropTypes.func.isRequired,
	itemSelected: PropTypes.string.isRequired,
	name: PropTypes.string.isRequired,
	placeholder: PropTypes.string.isRequired,
	hasError: PropTypes.string,
};

CustomPicker.defaultProps = {
	hasError: false,
};
