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

const ResultCard = ({ result, onAddToLibrary, cardNumber }) => {
    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.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>
                    ))}
                </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 [searchType, setSearchType] = useState('issues'); // State for search type
    const navigate = useNavigate();

    const filenames = [
        {
            name: 'Compilation of Judgments - Claimant',
            path: '\\001. Miscellaneous\\51. Section 16 Arbitration Act\\Compilation of Judgments- Claimant.pdf',
        },
        {
            name: 'Xerox Corporation and Ors vs PK Khansaheb and Ors',
            path: '\\001. Miscellaneous\\57.Additional documents\\Xerox_Corporation_and_Ors_vs_PK_Khansaheb_and_Ors_DE201819121816353171COM57952.pdf',
        },
        // Add other filenames here in the same format...
    ];

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

    const handleFileInputChange = (event) => {
        const value = event.target.value;
        setFileInput(value);
        if (value) {
            setFilteredFilenames(
                filenames.filter((file) =>
                    file.name.toLowerCase().includes(value.toLowerCase())
                )
            );
        } else {
            setFilteredFilenames(filenames);
        }
    };

    const handleSearchTypeChange = (event) => {
        setSearchType(event.target.value);
    };

    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 || '')}&type=${encodeURIComponent(searchType)}`
            );
            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">
                    <div className="dropdown">
                        <input
                            type="text"
                            placeholder="Type a file name to search..."
                            value={fileInput}
                            onChange={handleFileInputChange}
                            className="sidebar-input"
                        />
                        <div className="search-type">
                            <label>
                                <input 
                                    type="radio" 
                                    value="issues" 
                                    checked={searchType === 'issues'} 
                                    onChange={handleSearchTypeChange} 
                                />
                                Issues
                            </label>
                            <label>
                                <input 
                                    type="radio" 
                                    value="judgments" 
                                    checked={searchType === 'judgments'} 
                                    onChange={handleSearchTypeChange} 
                                />
                                Judgments
                            </label>
                        </div>
                        {/* Dropdown for filtered filenames */}
                        {fileInput && (
                            <div className="dropdown-content show">
                                {filteredFilenames.length > 0 ? (
                                    filteredFilenames.map((file, index) => {
                                        const relativePath = file.path
                                            .replace(/\\\\/g, '/')
                                            .replace(/.*GGN Office Repository\//, '');
                                        return (
                                            <a
                                                key={index}
                                                href={`http://192.168.2.5:3006/files/${encodeURIComponent(relativePath)}`}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="suggestion-item"
                                            >
                                                {file.name}
                                            </a>
                                        );
                                    })
                                ) : (
                                    <div className="no-suggestions">No matches found</div>
                                )}
                            </div>
                        )}
                    </div>
                </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}
                                            cardNumber={index + 1}
                                        />
                                    ))}
                                </div>
                            </>
                        ) : (
                            <div className="no-results">No results found</div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Home;    in theses i want to make two types of seraces in the sidebar...one for issues serach and other for judgments serach ....in issues we have to give only folder path