/**
 * Related Posts Component
 *
 * Displays list of related posts with search functionality.
 *
 * @package Purrlink
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { TextControl, Spinner } from '@wordpress/components';
import { Icon, search as searchIcon } from '@wordpress/icons';
import apiFetch from '@wordpress/api-fetch';

/**
 * Debounce hook.
 *
 * @param {string} value    Value to debounce.
 * @param {number} delay    Delay in milliseconds.
 * @return {string} Debounced value.
 */
const useDebounce = (value, delay) => {
	const [debouncedValue, setDebouncedValue] = useState(value);

	useEffect(() => {
		const handler = setTimeout(() => {
			setDebouncedValue(value);
		}, delay);

		return () => {
			clearTimeout(handler);
		};
	}, [value, delay]);

	return debouncedValue;
};

/**
 * Related Posts component.
 *
 * @param {Object}   props              Component props.
 * @param {Array}    props.posts        Array of related posts.
 * @param {Object}   props.selectedPost Currently selected post.
 * @param {number}   props.currentPostId Current post ID to exclude from search.
 * @param {Function} props.onSelect     Callback when post is selected.
 * @return {JSX.Element} Related posts component.
 */
const RelatedPosts = ({ posts, selectedPost, currentPostId, onSelect }) => {
	const [searchTerm, setSearchTerm] = useState('');
	const [searchResults, setSearchResults] = useState([]);
	const [isSearching, setIsSearching] = useState(false);

	// Debounce search term
	const debouncedSearch = useDebounce(searchTerm, 300);

	// Search posts when debounced term changes
	useEffect(() => {
		const searchPosts = async () => {
			if (!debouncedSearch || debouncedSearch.length < 2) {
				setSearchResults([]);
				return;
			}

			setIsSearching(true);

			try {
				const results = await apiFetch({
					path: `/purrlink/v1/search-posts?search=${encodeURIComponent(debouncedSearch)}&exclude=${currentPostId || 0}`,
				});
				setSearchResults(results);
			} catch {
				setSearchResults([]);
			} finally {
				setIsSearching(false);
			}
		};

		searchPosts();
	}, [debouncedSearch, currentPostId]);

	// Determine which posts to show
	const isSearchMode = searchTerm.length >= 2;
	const displayPosts = isSearchMode ? searchResults : posts;

	return (
		<div className="purrlink-related-posts">
			{/* Search Input */}
			<div className="purrlink-search">
				<Icon icon={searchIcon} className="purrlink-search__icon" size={18} />
				<TextControl
					className="purrlink-search__input"
					placeholder={__('Search all articles...', 'purrlink')}
					value={searchTerm}
					onChange={setSearchTerm}
				/>
			</div>

			{/* Search Mode Indicator */}
			{isSearchMode && (
				<div className="purrlink-search-mode">
					{isSearching ? (
						<span className="purrlink-search-mode__searching">
							<Spinner />
							{__('Searching...', 'purrlink')}
						</span>
					) : (
						<span className="purrlink-search-mode__results">
							{searchResults.length > 0
								? `${searchResults.length} ${__('results found', 'purrlink')}`
								: __('No results found', 'purrlink')}
						</span>
					)}
				</div>
			)}

			{/* Posts List */}
			{displayPosts.length > 0 ? (
				<ul className="purrlink-posts">
					{displayPosts.map((post) => (
						<li
							key={post.id}
							className={`purrlink-posts__item ${
								selectedPost?.id === post.id
									? 'purrlink-posts__item--selected'
									: ''
							}`}
							onClick={() => onSelect(post)}
							onKeyPress={(e) => {
								if (e.key === 'Enter') {
									onSelect(post);
								}
							}}
							role="button"
							tabIndex={0}
						>
							<div className="purrlink-posts__title">{post.title}</div>
							<div className="purrlink-posts__meta">
								{post.categories?.join(', ') || __('Uncategorized', 'purrlink')}
							</div>
						</li>
					))}
				</ul>
			) : (
				!isSearching && (
					<div className="purrlink-posts--empty">
						{isSearchMode
							? __('No matching articles found. Try different keywords.', 'purrlink')
							: __('No related articles found. Use search to find articles.', 'purrlink')}
					</div>
				)
			)}

			{/* Hint */}
			{!isSearchMode && posts.length > 0 && (
				<p className="purrlink-search-hint">
					{__('Tip: Search to find articles beyond related posts', 'purrlink')}
				</p>
			)}
		</div>
	);
};

export default RelatedPosts;
