import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './Home.css'; // Ensure your CSS is structured accordingly

const ResultCard = ({ result, onAddToLibrary, searchTerm, cardNumber }) => {
    const [isExpanded, setIsExpanded] = useState(false);

    return (
        <div className="result-card">
            <div className="result-header">
                <h3>
                    <span className="result-number">{cardNumber}.</span>
                    <a href={`http://192.168.2.5:3006/files/${result.relativePath}`} target="_blank" rel="noopener noreferrer">
                        {result.Filename.split('\\').pop()}
                    </a>
                </h3>
                <button onClick={() => onAddToLibrary(result)} className="add-button">
                    Add
                </button>
            </div>
            {result.matches.length > 0 ? (
                <div className="matches">
                    {result.matches.slice(0, isExpanded ? undefined : 1).map((match, index) => (
                        <div key={index} className="match-item">
                            <div>Page {match.page}</div>
                            <div
                                className="snippet"
                                dangerouslySetInnerHTML={{
                                    __html: match.snippet.replace(
                                        new RegExp(`(${match.keyword})`, 'gi'),
                                        '<mark>$1</mark>'
                                    ),
                                }}
                            />
                        </div>
                    ))}
                    {result.matches.length > 1 && (
                        <button
                            onClick={() => setIsExpanded(!isExpanded)}
                            className="show-more"
                        >
                            {isExpanded ? 'Show Less' : `Show More (${result.matches.length - 1})`}
                        </button>
                    )}
                </div>
            ) : (
                <p className="no-matches">No matches found</p>
            )}
        </div>
    );
};

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 [filteredFilenames, setFilteredFilenames] = useState([]);
    const [fileInput, setFileInput] = useState('');
    const navigate = useNavigate();

    // Replace this with your actual filenames
    const filenames = [
        "Document Example 1.pdf",
        "Document Example 2.pdf",
        "Another Document.pdf",
        "Sample File.pdf",
        // Add other filenames as necessary...
    ];

    useEffect(() => {
        setFilteredFilenames(filenames); // Initialize filtered filenames
    }, []);

    const handleFileInputChange = (event) => {
        const value = event.target.value;
        setFileInput(value);
        
        // Filter filenames based on user input
        if (value) {
            setFilteredFilenames(filenames.filter(filename =>
                filename.toLowerCase().includes(value.toLowerCase())
            ));
        } else {
            setFilteredFilenames(filenames);
        }
    };

    const handleFilenameSelect = (filename) => {
        setSearchTerm(filename); // Set search term to selected filename
        setFileInput(''); // Clear the input
        setFilteredFilenames(filenames); // Reset filtered filenames
    };

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

        setIsLoading(true);
        setError(null);

        try {
            const response = await fetch(
                `http://192.168.2.5:3006/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);
        } catch (error) {
            console.error(error);
            setError('Error fetching search results.');
        } finally {
            setIsLoading(false);
        }
    };

    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.2.5:3006/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.');
        }
    };

    return (
        <div className="app-container">
            {/* Sidebar */}
            <div className="sidebar">
                <div className="sidebar-header">
                    <h2>S&A Law Offices</h2>
                </div>
                <div className="sidebar-content">
                    <input 
                        type="text" 
                        placeholder="Type a file name to search..." 
                        value={fileInput} 
                        onChange={handleFileInputChange}
                        className="sidebar-input"
                    />
                    {/* Displaying filtered filenames */}
                    {fileInput && (
                        <ul className="suggestions-list">
                            {filteredFilenames.length > 0 ? (
                                filteredFilenames.map((filename, index) => (
                                    <li 
                                        key={index} 
                                        onClick={() => handleFilenameSelect(filename)} 
                                        className="suggestion-item"
                                    >
                                        {filename}
                                    </li>
                                ))
                            ) : (
                                <li className="no-suggestions">No matches found</li>
                            )}
                        </ul>
                    )}
                </div>
            </div>

            {/* Main Content */}
            <div className="main-content">
                <div className="search-container">
                    <form onSubmit={handleSubmit} className="search-form">
                        <input
                            type="text"
                            placeholder="Enter search term"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="search-input"
                        />
                        <input
                            type="text"
                            placeholder="Exclude words (optional)"
                            value={excludeWords}
                            onChange={(e) => setExcludeWords(e.target.value)}
                            className="search-input"
                        />
                        <button
                            type="submit"
                            disabled={isLoading}
                            className="search-button"
                        >
                            {isLoading ? 'Searching...' : 'Search'}
                        </button>
                    </form>

                    {error && <div className="error-message">{error}</div>}

                    <div className="results-section">
                        {isLoading ? (
                            <div className="loading">Loading...</div>
                        ) : searchResults.length > 0 ? (
                            <>
                                <div className="results-count">
                                    Found {searchResults.length} documents
                                </div>
                                <div className="results-list">
                                    {searchResults.map((result, index) => (
                                        <ResultCard
                                            key={index}
                                            result={result}
                                            onAddToLibrary={handleAddToLibrary}
                                            searchTerm={searchTerm}
                                            cardNumber={index + 1}
                                        />
                                    ))}
                                </div>
                            </>
                        ) : (
                            <div className="no-results">No results found</div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Home;   in this  i want the filename to be displaeyed in vertical format ...like this <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn {
  background-color: #04AA6D;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
  background-color: #3e8e41;
}

#myInput {
  box-sizing: border-box;
  background-image: url('searchicon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border-bottom: 1px solid #ddd;
}

#myInput:focus {outline: 3px solid #ddd;}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}
</style>
</head>
<body style="background-color:white;">

<h2>Search/Filter Dropdown</h2>
<p>Click on the button to open the dropdown menu, and use the input field to search for a specific dropdown link.</p>

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    <a href="#about">About</a>
    <a href="#base">Base</a>
    <a href="#blog">Blog</a>
    <a href="#contact">Contact</a>
    <a href="#custom">Custom</a>
    <a href="#support">Support</a>
    <a href="#tools">Tools</a>
  </div>
</div>

<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

function filterFunction() {
  const input = document.getElementById("myInput");
  const filter = input.value.toUpperCase();
  const div = document.getElementById("myDropdown");
  const a = div.getElementsByTagName("a");
  for (let i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}
</script>

</body>
</html>