import './css/Search.css'
import Sidebar from './Components/Sidebar'
import { default as axios } from 'axios'
import Cookies from 'js-cookie'
import SearchIcon from './icons/SearchIcon'
import VideoSearchResult from './Components/VideoSearchResult'
import { config } from './main'
import React, { useRef } from 'react'
import { createRoot } from 'react-dom/client';

let searchResults;
let searched;
let searchResultsRef;
let searchStatusRef;

async function search2() {
	const searchBar = document.getElementById("search-bar");
	if(searchBar.value.trim() != "") {
		if(!searched) searchResults = createRoot(searchResultsRef.current);
		if(searched) { searchResults.unmount(); searchResults = createRoot(searchResultsRef.current); }
		searched = true;

		searchStatusRef.current.innerText = "searching!!";
		const response = await axios.post(`${config.serverURL}/video/search`, {
			"query": searchBar.value
		})

		if(!response.error) {
			if(response.data.length === 0) {
				return searchStatusRef.current.innerText = "no results :(";
			}

			response.data.forEach(video => {
				console.log(video)
				searchResults.render(<VideoSearchResult 
					id={video.id}
					title={video.title}
					author={video.author.username}
					likes={video.likes}
					dislikes={video.dislikes}
					comments={video.comments}
					shares={video.shares}
				/>)
			})
		} else {
			searchStatusRef.current.innerText = `search error: ${response.error}`;
		}
	} else {
		searchStatusRef.current.innerText = `no`;
	}
}

function Search() {
	searchResultsRef = useRef(null);
	searchStatusRef = useRef(null);

	return (
		<>
			<div className="main">
				<Sidebar />
				<div className="search-container">
					<div className="search-bar-container">
						<button className="search-button" onClick={() => {search2(searchResults)}}>
							<SearchIcon size={50} />
						</button>
						<input type="text" placeholder="Search" className="search-bar" id="search-bar" />
					</div>

					<div className="search-results" id="search-results" ref={searchResultsRef}>
						<div className="search-status" ref={searchStatusRef}>
							
						</div>
					</div>
				</div>
			</div>
		</>
	)
}

export default Search
