import { useEffect, useRef, useState } from "react";
import { FaDownload } from "react-icons/fa";
import { toast } from "sonner";
import Container from "../Container";
import NavBar from "../NavBar";

function Cache() {
    const [searchQuery, setSearchQuery] = useState("");
    const [cacheData, setCacheData] = useState([]);
    const [keyCount, setKeyCount] = useState(0);
    const [loading, setLoading] = useState(false);
    const [hasSearched, setHasSearched] = useState(false);

    const debounceTimeout = useRef(null);

    // Fetch the key count when the component mounts
    useEffect(() => {
        const fetchKeyCount = async () => {
            try {
                const response = await fetch("/api/cache/keycount");
                const data = await response.json();
                setKeyCount(data.count); // Update key count
            } catch (error) {
                console.error("Error fetching key count:", error);
            }
        };

        fetchKeyCount();
    }, []); // Run only once when the component mounts

    const handleInputChange = (event) => {
        const query = event.target.value;
        setSearchQuery(query);

        if (debounceTimeout.current) {
            clearTimeout(debounceTimeout.current);
        }

        if (query.trim() !== "") {
            setLoading(true); // Show spinner immediately
            debounceTimeout.current = setTimeout(() => {
                sendApiCall(query);
            }, 1000);
        } else {
            setHasSearched(false); // Reset state when input is cleared
            setCacheData([]);
        }
    };

    const sendApiCall = (text) => {
        setLoading(true);
        fetch("/api/cache/search", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ input: text }),
        })
            .then((response) => response.json())
            .then((data) => {
                setCacheData(data);
                setHasSearched(true);
            })
            .catch((error) => {
                toast.error(`Error: ${error.message}`);
                console.error("Error:", error);
            })
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        document.title = "Cache | CDRM-Project";
    }, []);

    return (
        <>
            <NavBar />
            <Container>
                <div className="my-4 flex w-full flex-col items-center justify-center gap-2 lg:flex-row">
                    <fieldset className="fieldset w-full max-w-2xl">
                        <input
                            type="text"
                            value={searchQuery}
                            onChange={handleInputChange}
                            placeholder={`Search ${keyCount} keys...`}
                            className="input w-full max-w-2xl font-mono"
                        />
                    </fieldset>
                    <button
                        className="btn btn-success"
                        onClick={() => {
                            window.location.href = "/api/cache/download";
                        }}
                    >
                        <FaDownload />
                        Download keys cache
                    </button>
                </div>

                {loading ? (
                    <div className="flex justify-center py-16">
                        <span className="loading loading-spinner loading-md me-2"></span>
                        Searching...
                    </div>
                ) : cacheData.length > 0 ? (
                    <div className="my-4 flex justify-center">
                        <div className="overflow-x-auto">
                            <table className="table">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th className="text-center">PSSH</th>
                                        <th className="text-center">key ID:key pair</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {cacheData.map((item, index) => (
                                        <tr key={index}>
                                            <th>{index + 1}</th>
                                            <td className="font-mono">{item.PSSH}</td>
                                            <td className="font-mono">
                                                {item.KID}:{item.Key}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                ) : hasSearched ? (
                    <div className="flex justify-center py-16">
                        <div className="text-center">No data found in the database</div>
                    </div>
                ) : (
                    <div className="flex justify-center py-16">
                        <div className="text-center">Enter a search query to see results</div>
                    </div>
                )}
            </Container>
        </>
    );
}

export default Cache;
