import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './Home.css';  // We'll create this CSS file next

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 navigate = useNavigate();

    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">
                    <select className="sidebar-select">
                        <option value="">Choose search type...</option>
                        <option value="option1">Option 1</option>
                        <option value="option2">Option 2</option>
                    </select>
                </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;   THS IS HOME.JS     ..../* Base Layout */
.app-container {
  display: flex;
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* Sidebar */
.sidebar {
  width: 300px;
  background-color: #f8f9fa;
  box-shadow: 1px 0 3px rgba(0, 0, 0, 0.1);
  padding: 2rem 1.5rem;
}

.sidebar-header {
  margin-bottom: 1.5rem;
}

.sidebar-header h2 {
  color: #333;
  font-size: 1.25rem;
  font-weight: 500;
}

.sidebar-select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.375rem;
  background-color: white;
  color: #4a5568;
  font-size: 0.95rem;
}

/* Main Content */
.main-content {
  flex: 1;
  padding: 2rem;
  background-color: white;
}

.search-container {
  max-width: 900px;
  margin: 0 auto;
}

/* Search Form */
.search-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 2rem;
}

.search-input {
  padding: 0.75rem 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.375rem;
  font-size: 0.95rem;
  transition: border-color 0.15s ease-in-out;
}

.search-input:focus {
  outline: none;
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
}

.search-button {
  padding: 0.75rem 1.5rem;
  background-color: #48bb78;
  color: white;
  border: none;
  border-radius: 0.375rem;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.15s ease-in-out;
}

.search-button:hover {
  background-color: #38a169;
}

.search-button:disabled {
  background-color: #9ae6b4;
  cursor: not-allowed;
}

/* Results Section */
.results-section {
  margin-top: 2rem;
}

.results-count {
  color: #4a5568;
  font-size: 0.95rem;
  margin-bottom: 1.5rem;
}

.result-card {
  background-color: white;
  border: 1px solid #e2e8f0;
  border-radius: 0.5rem;
  padding: 1.25rem;
  margin-bottom: 1rem;
  transition: box-shadow 0.15s ease-in-out;
}

.result-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.result-header h3 {
  font-size: 1rem;
  font-weight: 500;
  color: #2d3748;
  margin: 0;
}

.result-number {
  color: #718096;
  margin-right: 0.5rem;
}

.add-button {
  padding: 0.5rem 1rem;
  background-color: #4299e1;
  color: white;
  border: none;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.15s ease-in-out;
}

.add-button:hover {
  background-color: #3182ce;
}

/* Matches */
.matches {
  font-size: 0.95rem;
  color: #4a5568;
}

.match-item {
  padding: 0.75rem;
  background-color: #f8f9fa;
  border-radius: 0.375rem;
  margin-bottom: 0.75rem;
}

.snippet {
  margin-top: 0.5rem;
  line-height: 1.5;
}

mark {
  background-color: #fefcbf;
  padding: 0.125rem 0.25rem;
  border-radius: 0.125rem;
}

.show-more {
  color: #4299e1;
  background: none;
  border: none;
  padding: 0.5rem 0;
  font-size: 0.875rem;
  cursor: pointer;
  transition: color 0.15s ease-in-out;
}

.show-more:hover {
  color: #3182ce;
}

/* Status Messages */
.error-message {
  color: #e53e3e;
  padding: 0.75rem;
  background-color: #fff5f5;
  border-radius: 0.375rem;
  margin-bottom: 1rem;
}

.loading, .no-results {
  text-align: center;
  color: #718096;
  padding: 2rem;
  font-size: 0.95rem;
}    i wnated the app.conatiner to take full width and height of the page ....just like straemlit i wanted the sidebar to start from leftest