import React, { useState } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import './Home.css'; 
import { useSearchContext } from '../context/searchcontext'; 

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

    const handleSearchTermChange = (event) => {
        setSearchTerm(event.target.value);
    };

    const handleExcludeWordsChange = (event) => {
        setExcludeWords(event.target.value);
    };

    const handleSubmit = async (event) => {
        event.preventDefault();
        setIsLoading(true);
        setError(null);

        try {
            const response = await fetch(`http://192.168.7.175:3005/search?keyword=${encodeURIComponent(searchTerm)}`);
            if (!response.ok) throw new Error('Network response was not ok');

            const data = await response.json();
            setSearchResults(data); 
            setError(null);
        } catch (error) {
            console.error('Error fetching search results:', error);
            setError('Failed to fetch search results.');
        } finally {
            setIsLoading(false);
        }
    };

    const addToLibrary = (filename) => {
       
    };

    const clearResults = () => {
        setSearchResults([]);
    };

   
    const getRelativePath = (fullPath) => {
        const basePath = '\\\\192.168.13.30\\c$\\GGN Office Repository\\';
        if (fullPath.startsWith(basePath)) {
            return fullPath.slice(basePath.length).replace(/\\/g, '/');
        }
        return fullPath.replace(/\\/g, '/');
    };

    return (
        <div className="app-container">
            <Navbar />
            <main>
                <div className="container">
                    <div id="ball"></div>
                    <p id="xyz">S&A Law Offices</p>
                </div>
                <form onSubmit={handleSubmit}>
                    <div className="search-input">
                        <input
                            type="text"
                            placeholder="Enter text"
                            value={searchTerm}
                            onChange={handleSearchTermChange}
                            required
                        />
                        <input
                            type="text"
                            placeholder="Exclude these words (Optional)"
                            value={excludeWords}
                            onChange={handleExcludeWordsChange}
                        />
                        <button type="submit">Search</button>
                    </div>
                </form>
                
                {isLoading && <p>Searching...</p>}
                {error && <p style={{ color: 'red' }}>{error}</p>}
                <br />
                <div>
                    {searchResults.length > 0 ? (
                        <div className="scrollable-container">
                            <p>{searchResults.length} document(s) found:</p>
                            <ul style={{ listStyleType: 'none', padding: 0 }}>
                                {searchResults.map((result, index) => {
                                    const relativePath = getRelativePath(result.Filename);
                                    const encodedPath = encodeURI(relativePath);

                                    return (
                                        <li key={index} style={{ margin: '5px 0', position: 'relative' }}>
                                            <a 
                                                href={`http://192.168.7.175:3005/files/${encodedPath}`} 
                                                target="_blank" 
                                                rel="noopener noreferrer"
                                                style={{ color: 'blue', textDecoration: 'underline' }}
                                            >
                                                {relativePath}
                                            </a> 

                                            <span 
                                                className="add-to-library" 
                                                onClick={() => addToLibrary(result.filename)} 
                                                title="Add to Library"
                                                style={{
                                                    marginLeft: '10px',
                                                    cursor: 'pointer',
                                                    color: 'green',
                                                    fontSize: '20px',
                                                    display: 'inline-block',
                                                }}
                                            >
                                                &#43; {/* Plus symbol */}
                                            </span>
                                        </li>
                                    )
                                })}
                            </ul>
                        </div>
                    ) : (
                        !isLoading && <p>No results found.</p>
                    )}
                </div>
            </main>
            <Footer />
        </div>
    );
};

export default Home;    
in this apply add to my library functionality on clicking the plus icon and word and hits add in search history page