import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ResultCard from '../components/Resultcard'; // Ensure the path is correct
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 [filteredFilenames, setFilteredFilenames] = useState([]);
    const [fileInput, setFileInput] = useState('');
    const [searchType, setSearchType] = useState('issues');
    const navigate = useNavigate();

    const filenames = [
        {
            name: 'Compilation of Judgments - Claimant',
            path: 'file://192.168.13.30/c$/GGN%20Office%20Repository/001.%20Miscellaneous/51.%20Section%2016%20Arbitration%20Act/Compilation%20of%20Judgments-%20Claimant.pdf',
        },
        {
            name: '01.NHAI Rayalseema Expressway Pvt.Ltd..pdf',
            path: 'file://192.168.13.30/c$/GGN%20Office%20Repository/Actual%20proof%20of%20loss%20not%20required%20-%20MoRTH%20SDB%20calculation/01.%20NHAI%20v.%20Rayalseema%20Expressway%20Pvt.%20Ltd..pdf',
        },
    ];

    const issueFiles = [
        {
            name: 'Administrative authority cannot exercise power when matter is subjudice,pending',
            path: 'file://192.168.13.30/c$/GGN%20Office%20Repository/Administrative%20authority%20cannot%20exercise%20power%20when%20matter%20is%20sub%20judice,%20pending/',
        },
        {
            name: 'Another Issue',
            path: 'file://192.168.13.30/c$/GGN%20Office%20Repository/AnotherIssue.pdf',
        },
    ];

    useEffect(() => {
        setFilteredFilenames(searchType === 'issues' ? issueFiles : filenames);
    }, [searchType]);

    const handleSearchTypeChange = (event) => {
        const value = event.target.value;
        setSearchType(value);
        setFileInput('');
        setFilteredFilenames(value === 'issues' ? issueFiles : filenames);
    };

    const handleFileInputChange = (event) => {
        const value = event.target.value;
        setFileInput(value);
        if (value) {
            setFilteredFilenames(
                (searchType === 'issues' ? issueFiles : filenames).filter((file) =>
                    file.name.toLowerCase().includes(value.toLowerCase())
                )
            );
        } else {
            setFilteredFilenames(searchType === 'issues' ? issueFiles : 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 || ''
                )}&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);
        }
    };

    return (
        <div className="app-container">
            <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={searchType === 'issues' ? 'Type an issue to search...' : 'Type a filename 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>
                        {fileInput && (
                            <div className="dropdown-content show">
                                {filteredFilenames.length > 0 ? (
                                    filteredFilenames.map((file, index) => (
                                        <a
                                            key={index}
                                            href={file.path}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="suggestion-item"
                                        >
                                            {file.name}
                                        </a>
                                    ))
                                ) : (
                                    <div className="no-suggestions">No matches found</div>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </div>

            <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}
                                            cardNumber={index + 1}
                                            searchType={searchType}
                                        />
                                    ))}
                                </div>
                            </>
                        ) : (
                            <div className="no-results">No results found</div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Home;

   in this make the cards odf judgements and issues to be scrollbar ....add css to them adjust reposnivenesss import React from 'react';

const ResultCard = ({ result, cardNumber, searchType }) => {
    const openFile = (filePath) => {
        if (filePath.startsWith('file://')) {
            window.open(filePath, '_blank', 'noopener,noreferrer');
        } else {
            console.warn('Invalid file path:', filePath);
        }
    };

    return (
        <div className="result-card">
            <div className="result-header">
                <h3>
                    <span className="result-number">{cardNumber}.</span>
                    <span
                        onClick={() => openFile(result.path)}
                        style={{ cursor: 'pointer', color: 'blue', textDecoration: 'underline' }}
                    >
                        {result.name}
                    </span>
                </h3>
            </div>
        </div>
    );
};

export default ResultCard;
     and on clciking the name of judgment or issue it is not opening up the link ...make them clikble ....abhi m link cpcoy krke kholti hi toh chl jata h ....pr mjhe lcick pr kholna h