import React, { useState, useRef, useEffect } from 'react';
import type { FC, KeyboardEvent, MouseEvent } from 'react';

interface KeywordInputProps {
    keywords: string[];
    onChange: (keywords: string[]) => void;
    getString: (category: string, key: string, fallback?: string) => string;
}

const KeywordInput: FC<KeywordInputProps> = ({
    keywords,
    onChange,
    getString,
}) => {
    const [inputValue, setInputValue] = useState('');
    const [suggestions, setSuggestions] = useState<string[]>([]);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const inputRef = useRef<HTMLInputElement>(null);

    // Common keywords for suggestions - this could be fetched from an API or passed as props
    const commonKeywords = [
        'SEO',
        'Marketing',
        'Social Media',
        'Content Strategy',
        'Analytics',
        'Digital Marketing',
        'Blogging',
        'WordPress',
        'Web Design',
        'E-commerce',
    ];

    const handleInputChange = (value: string) => {
        setInputValue(value);

        // Filter suggestions based on input
        if (value.trim()) {
            const filtered = commonKeywords.filter(
                keyword =>
                    keyword.toLowerCase().includes(value.toLowerCase()) &&
                    !keywords.includes(keyword)
            );
            setSuggestions(filtered);
            setShowSuggestions(true);
        } else {
            setSuggestions([]);
            setShowSuggestions(false);
        }
    };

    const addKeyword = (keyword: string) => {
        const trimmedKeyword = keyword.trim();
        if (trimmedKeyword && !keywords.includes(trimmedKeyword)) {
            onChange([...keywords, trimmedKeyword]);
        }
        setInputValue('');
        setSuggestions([]);
        setShowSuggestions(false);
    };

    const removeKeyword = (indexToRemove: number) => {
        onChange(keywords.filter((_, index) => index !== indexToRemove));
    };

    const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            addKeyword(inputValue);
        } else if (
            e.key === 'Backspace' &&
            !inputValue &&
            keywords.length > 0
        ) {
            removeKeyword(keywords.length - 1);
        }
    };

    const handleSuggestionClick = (suggestion: string) => {
        addKeyword(suggestion);
        if (inputRef.current) {
            inputRef.current.focus();
        }
    };

    // Close suggestions when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent | any) => {
            if (inputRef.current && !inputRef.current.contains(event.target)) {
                setShowSuggestions(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    return (
        <div className="cpepai-keyword-input">
            <div className="cpepai-keyword-tags">
                {keywords.map((keyword, index) => (
                    <span key={index} className="cpepai-keyword-tag">
                        {keyword}
                        <button
                            type="button"
                            onClick={() => removeKeyword(index)}
                            className="cpepai-keyword-remove"
                            aria-label={getString(
                                'content_plan_table',
                                'remove_keyword',
                                'Remove keyword'
                            )}
                        >
                            ×
                        </button>
                    </span>
                ))}
                <input
                    ref={inputRef}
                    type="text"
                    value={inputValue}
                    onChange={e => handleInputChange(e.target.value)}
                    onKeyDown={handleKeyDown}
                    onFocus={() => setShowSuggestions(!!inputValue)}
                    className="cpepai-keyword-input-field"
                    placeholder={
                        keywords.length === 0
                            ? getString(
                                  'content_plan_table',
                                  'keywords_placeholder',
                                  'Type keywords and press Enter...'
                              )
                            : ''
                    }
                />
            </div>
            {showSuggestions && suggestions.length > 0 && (
                <div className="cpepai-keyword-suggestions">
                    {suggestions.map((suggestion, index) => (
                        <button
                            key={index}
                            type="button"
                            onClick={() => handleSuggestionClick(suggestion)}
                            className="cpepai-keyword-suggestion"
                        >
                            {suggestion}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
};

export default KeywordInput;
