import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { AutoComplete, Input, Rate } from 'antd';
import { fetchSearchSuggestions } from '@lib/redux/actions/search-actions';


interface SBI {
	suggestions?,
	fetchSearchSuggestions?,
	general?,
	status?
}


const
	SearchBarComponent = ({ suggestions, fetchSearchSuggestions, general, status }: SBI) => {
		const renderTitle = (title: string, url: string) => {
			return (<>
				{title}
				<a style={{ float: 'right' }} href={url}>Find more</a>
			</>);
		};

		const renderItem = (title: string, url, count: number | { weight: number }) => {
			return {
				value: title,
				label: (
					<div style={{ display: 'flex', justifyContent: 'space-between', }} >
						<a href={url}>{title?.length > 40 ? title?.substr(0, 40) + '...' : title}</a>
						{
							typeof (count) == 'number'
								? (<>
									<span> Ads: {count} </span>
								</>)
								: typeof (count) == 'string'
									? (
										<>
											<span>{count}</span>
										</>
									)
									: (<Rate disabled defaultValue={count?.weight} />)
						}
					</div>
				),
			};
		};

		const renderNotGeneral = sug => {
			return sug?.options?.map(op => ({
				value: op.name,
				label: (
					<div
						style={{
							display: 'flex',
							justifyContent: 'space-between',
						}}
					>
						<span>
							<a
								href={op.url}
							>
								{op.title?.length > 40 ? op.title?.substr(0, 40) + '...' : op.title}
							</a>
						</span>
						<span><Rate disabled defaultValue={op.rating?.weight} /></span>
					</div>
				)
			}));
		};

		const lookUpOptions = general ? suggestions?.map(sug => {
			return {
				label: renderTitle(sug.title, sug.url),
				options: sug.options.map(op => renderItem(op.title, op.url, op.ads_count ? op.ads_count : op.date ? op.date : op.rating))
			};
		}) : renderNotGeneral(suggestions?.find(sug => sug.title == 'Ads'));

		const
			[initialType, setInitialType] = React.useState(null),
			onChange = data => {
				setInitialType(data);
				setTimeout(() =>
					data && data.substr(0, data.length - 1) == initialType ? fetchSearchSuggestions(data) : null
				, 2e3);
			};

		return (
			<AutoComplete
				dropdownClassName="certain-category-search-dropdown"
				dropdownMatchSelectWidth={500}
				style={{ width: 250 }}
				options={lookUpOptions}
				onChange={onChange}
			>
				<Input.Search loading={status?.suggestions?.fetching} size="small" placeholder="Type a keyword to search" />
			</AutoComplete>
		);
	},
	mapStateToProps = state => state,
	mapDispatchToProps = dispatch => bindActionCreators({
		fetchSearchSuggestions
	},
	dispatch),
	SearchBar = connect(mapStateToProps, mapDispatchToProps)(SearchBarComponent);



export default SearchBar;
