import React, { useState, useEffect } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import { useNavigate } from 'react-router-dom';
import './Home.css';

const Home = () => {
    const [searchTerm, setSearchTerm] = useState('');
    const [excludeWords, setExcludeWords] = useState('');
    const [searchResults, setSearchResults] = useState([]);
    const [error, setError] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    const [totalMatches, setTotalMatches] = useState(0);

    const navigate = useNavigate();

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (!token) {
            console.log("User is not logged in");
        }
    }, []);

    // Handle search term input
    const handleSearchTermChange = (event) => {
        setSearchTerm(event.target.value);
    };

    // Handle exclude-word input
    const handleExcludeWordsChange = (event) => {
        setExcludeWords(event.target.value);
    };

    // Add to Library Action
    const handleAddToLibrary = async (pdf) => {
        const token = localStorage.getItem('token');
        if (!token) {
            navigate('/login', {
                state: {
                    message: 'Please log in to add documents to your library',
                    redirectAfterLogin: '/home',
                },
            });
            return;
        }

        try {
            const response = await fetch('http://192.168.7.206:3007/api/lib/library/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`,
                },
                body: JSON.stringify({
                    filename: pdf.relativePath,
                    originalFilePath: pdf.Filename,
                }),
            });

            if (response.ok) {
                alert('Document added to library');
            } else {
                const errorData = await response.json();
                alert(errorData.message || 'Failed to add document to library');
            }
        } catch (error) {
            console.error('Error adding to library:', error);
            alert('Network error. Please try again.');
        }
    };

    
    const handleSubmit = async (event) => {
        event.preventDefault();
        
        if (!searchTerm.trim()) {
            setError('Please enter a search term.');
            return;
        }

        setIsLoading(true);
        setError(null);
        setSearchResults([]); // Clear previous results
        setTotalMatches(0); // Reset total matches

        try {
            const response = await fetch(
                `http://192.168.7.206:3007/search?keyword=${encodeURIComponent(searchTerm)}&exclude=${encodeURIComponent(
                    excludeWords || ''
                )}`
            );
            if (!response.ok) {
                throw new Error('Failed to fetch search results');
            }
            const data = await response.json();

            setSearchResults(data);
            setTotalMatches(data.length); 
        } catch (error) {
            console.error(error);
            setError('Error fetching search results.');
        } finally {
            setIsLoading(false);
        }
    };

    // Handle Snippet Page Redirection
    const handleSnippetClick = (relativePath, page) => {
        const pdfUrl = `http://192.168.7.206:3007/files/${encodeURIComponent(relativePath)}#page=${page + 1}`;
        window.open(pdfUrl, '_blank');
    };

    return (
        <div className="app-container">
            <Navbar />
            <main>
                
                <form onSubmit={handleSubmit} className="search-form">
                    <input
                        type="text"
                        placeholder="Enter search term"
                        value={searchTerm}
                        onChange={handleSearchTermChange}
                        className="search-input"
                    />
                    <input
                        type="text"
                        placeholder="Exclude words (optional)"
                        value={excludeWords}
                        onChange={handleExcludeWordsChange}
                        className="exclude-input"
                    />
                    <button
                        type="submit"
                        className="search-button"
                        disabled={isLoading}
                    >
                        {isLoading ? 'Searching...' : 'Search'}
                    </button>
                </form>

                {/* Error Message */}
                {error && <p className="error-message">{error}</p>}

                {/* Loading or Total Matches */}
                {isLoading && !error && (
                    <p className="loading">
                        There are <strong>{totalMatches || '...'}</strong> matches for your search. Please wait...
                    </p>
                )}

                {/* Search Results */}
                <div className="results-container">
                    {!isLoading && totalMatches > 0 && (
                        <p className="total-matches">
                            Total Documents Found: <strong>{totalMatches}</strong>
                        </p>
                    )}
                    {!isLoading && searchResults.length > 0 ? (
                        <div className="scrollable-container">
                            {searchResults.map((result, index) => (
                                <ResultCard
                                    key={index}
                                    index={index + 1} // Add index to card
                                    result={result}
                                    handleSnippetClick={handleSnippetClick}
                                    onAddToLibrary={handleAddToLibrary}
                                    searchTerm={searchTerm}
                                />
                            ))}
                        </div>
                    ) : !isLoading && <p>No results found</p>}
                </div>
            </main>
            <Footer />
        </div>
    );
};

const ResultCard = ({ result, index, handleSnippetClick, onAddToLibrary, searchTerm }) => {
    const [isExpanded, setIsExpanded] = useState(false);
    const searchTerms = searchTerm.split('+').map(term => term.trim()).filter(Boolean); // Split search terms

    return (
        <div className="result-card">
            <div className="result-header">
                <h3 className="filename">
                    <span className="index">{index}.</span>{' '}
                    <a
                        href={`http://192.168.7.206:3007/files/${result.relativePath}`}
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        {result.Filename.split('\\').pop()}
                    </a>
                </h3>
                <button
                    className="add-to-library-button"
                    onClick={() => onAddToLibrary(result)}
                    title="Add to Library"
                >
                    Add
                </button>
            </div>
            <p className="relative-path">
                <strong>Location:</strong> {result.relativePath}
            </p>

            {result.matches.length > 0 ? (
                <div className="matches">
                    {searchTerms.map((term, termIndex) => (
                        <div key={termIndex}>
                            <h4>Matches for <strong>{term}</strong>:</h4>
                            {result.matches
                                .filter(match => match.snippet.includes(term))
                                .map((match, matchIndex) => (
                                    <div
                                        key={matchIndex}
                                        className="match-snippet"
                                        onClick={() =>
                                            handleSnippetClick(result.relativePath, match.page)
                                        }
                                    >
                                        <strong>Page {match.page + 1}:</strong>{' '}
                                        <span
                                            className="snippet-text"
                                            dangerouslySetInnerHTML={{
                                                __html: match.snippet.replace(
                                                    new RegExp(`(${term})`, 'gi'),
                                                    '<b style="color:red;">$1</b>' // Highlight with style
                                                ),
                                            }}
                                        />
                                    </div>
                                ))}
                        </div>
                    ))}
                </div>
            ) : (
                <p className="no-matches">No matches found in this file.</p>
            )}
        </div>
    );
};
export default Home;   not dispallying sniippets for boolean seraches