import React from 'react';

import classNames from 'classnames';

import { BuilderModule, PropUrl } from '../../../@types/settings.js';
import getProvider from '../../utils/getProvider.js';

import './CtrlUrl.scss';

const PROVIDER = getProvider();

type ControlProps = {
	updateProps: (id: string, path: string, value: any) => void;
	deleteProp: (path: string) => void;
	currMod: BuilderModule;
	updatePath: string;
	prop: PropUrl;
	value: any;
	inheritVal?: boolean;
};

export default function CtrlUrl({
	currMod,
	updatePath,
	prop,
	value,
	inheritVal,
	deleteProp,
	updateProps,
}: ControlProps) {
	const { search } = prop;

	const [searchResults, setSearchResults] = React.useState<
		{ label: string; slug?: string; value: string }[]
	>([]);
	const [searchValue, setSearchValue] = React.useState<string>('');
	const [searchTimeout, setSearchTimeout] = React.useState<any>(null);

	async function onSearch(searchValue: string) {
		const searchResults = await (search ?? PROVIDER.searchUrls)(searchValue);
		setSearchResults(searchResults);
	}

	React.useEffect(() => {
		if (searchValue && searchValue.trim().length > 0) {
			onSearch(searchValue);
		} else {
			setSearchResults([]);
		}
	}, [searchValue]);

	function onChange(e: React.ChangeEvent<HTMLInputElement>) {
		console.log('here', e.target.value);

		if (searchTimeout) {
			clearTimeout(searchTimeout);
		}
		setSearchTimeout(
			setTimeout(() => {
				setSearchValue(e.target.value);
			}, 500)
		);

		if (e.target.value && e.target.value.trim().length > 0) {
			updateProps(currMod.id, updatePath, e.target.value);
			return;
		}

		if (searchTimeout) {
			clearTimeout(searchTimeout);
			setSearchResults([]);
		}

		deleteProp(updatePath);
	}

	const [blurTimeout, setBlurTimeout] = React.useState<any>(null);

	function onBlur() {
		if (blurTimeout) {
			clearTimeout(blurTimeout);
		}
		setBlurTimeout(
			setTimeout(() => {
				setSearchResults([]);
			}, 300)
		);
	}

	function onFocus() {
		if (blurTimeout) {
			clearTimeout(blurTimeout);
		}
	}

	return (
		<div className='ctrl-search'>
			<input
				key={currMod.id + updatePath}
				className={classNames('ctrl-search__input', {
					'ctrl-search__input--has-results': searchResults.length > 0,
				})}
				type='text'
				placeholder={inheritVal ? value : ''}
				value={inheritVal ? '' : value}
				onChange={onChange}
				onBlur={onBlur}
				onFocus={onFocus}
			/>
			{searchResults.length > 0 && (
				<div className='ctrl-search__results'>
					{searchResults.map((result, index) => (
						<div
							key={index}
							className='ctrl-search__result'
							onClick={() => {
								if (blurTimeout) {
									clearTimeout(blurTimeout);
								}
								setSearchResults([]);
								updateProps(currMod.id, updatePath, result.value);
							}}
						>
							{result.label}{' '}
							{result.slug && (
								<span
									title={`/${result.slug.replaceAll('/', '')}`}
									className='ctrl-search__result__slug'
								>
									/{result.slug.replaceAll('/', '')}
								</span>
							)}
						</div>
					))}
				</div>
			)}
		</div>
	);
}
