import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { ChevronRight, Search } from 'lucide-react';

/**
 * Gleap-style "Search for help" card: a search field that filters the help
 * questions, followed by the matching questions. Picking a question (or
 * submitting the search) starts a new chat with that text.
 */
const HelpSearchCard = ({ questions = [], onSelect, limit = 5, disabled = false }) => {
    const [query, setQuery] = useState('');

    const list = (Array.isArray(questions) ? questions : []).filter((q) => typeof q === 'string' && q.trim() !== '');
    const term = query.trim().toLowerCase();
    const matches = (term ? list.filter((q) => q.toLowerCase().includes(term)) : list).slice(0, limit);

    if (list.length === 0) return null;

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!term || disabled) return;
        onSelect(query.trim());
        setQuery('');
    };

    return (
        <div className="aisk-help-search">
            <form className="aisk-help-search-field" onSubmit={handleSubmit}>
                <input
                    type="text"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    placeholder={__( 'Search for help', 'aisk-ai-chat' )}
                    aria-label={__( 'Search for help', 'aisk-ai-chat' )}
                    disabled={disabled}
                />
                <button type="submit" aria-label={__( 'Search', 'aisk-ai-chat' )} disabled={disabled}>
                    <Search size={18} />
                </button>
            </form>

            {matches.map((question, index) => (
                <button
                    key={index}
                    type="button"
                    className="aisk-question-item"
                    onClick={() => onSelect(question)}
                    disabled={disabled}
                >
                    <span>{question}</span>
                    <ChevronRight size={16} className="aisk-card-chevron" />
                </button>
            ))}

            {term && matches.length === 0 && (
                <button type="button" className="aisk-question-item" onClick={handleSubmit} disabled={disabled}>
                    <span>
                        {__( 'Ask:', 'aisk-ai-chat' )} <strong>{query.trim()}</strong>
                    </span>
                    <ChevronRight size={16} className="aisk-card-chevron" />
                </button>
            )}
        </div>
    );
};

export default HelpSearchCard;
