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": "001. Miscellaneous",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/001. Miscellaneous"
        },
        {
            "name": "19(4), arbitration act - Admissibility, relevancy, materiality",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/19(4), arbitration act - Admissibility, relevancy, materiality"
        },
        {
            "name": "001. Miscellaneous",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/001. Miscellaneous"
        },
        {
            "name": "19(4), arbitration act - Admissibility, relevancy, materiality",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/19(4), arbitration act - Admissibility, relevancy, materiality"
        },
        {
            "name": "001. Miscellaneous",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/001. Miscellaneous"
        },
        {
            "name": "19(4), arbitration act - Admissibility, relevancy, materiality",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/19(4), arbitration act - Admissibility, relevancy, materiality"
        },

        

    ]
    
    const issueFiles = [
        {
            "name": "001. Miscellaneous",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/001. Miscellaneous"
        },
        {
            "name": "19(4), arbitration act - Admissibility, relevancy, materiality",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/19(4), arbitration act - Admissibility, relevancy, materiality"
        },
        {
            "name": "001. Miscellaneous",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/001. Miscellaneous"
        },
        {
            "name": "19(4), arbitration act - Admissibility, relevancy, materiality",
            "path": "file://192.168.13.30/c$//192.168.13.30/c$/GGN Office Repository/19(4), arbitration act - Admissibility, relevancy, materiality"
        },

    ]
    

    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 in sidebar add some css to make tje dropdown lis look good and add scrol feature ..responsivr also