import { SearchedUserFilesList } from '@/app/ui/search/searched-user-files-list';
import { SearchedGlobalFilesList } from '@/app/ui/search/searched-global-files-list';
import { useCallback, useState, useImperativeHandle } from 'react';
import { searchUserFiles, searchGlobalFiles } from '@/app/actions/searchActions';
import { useQueryClient } from '@tanstack/react-query';
import { Pagination } from '@/app/components/Pagination';
import { useTranslations } from 'next-intl';
import { AllowedExtensions } from '@/app/ui/search/section-search-file';
export interface SearchItem {
	url: string,
	pageTitle: string,
	height: number,
	width: number,
	host: string,
	pageUrl: string
}

export interface FileInfo {
	fileId: string,
	fileSize: number,
	hammingDistance: number,
	originalFileName: string,
	ownerId: number,
	similarityLevel: string,
	status: string,
	supportId: number,
	uploadDate: string,
	url: string
}

export function FileSearchPanel(
	{ fileId, ref, allowedExtensions, fileType }
		:
		{ fileId: string | null, ref: any, allowedExtensions: AllowedExtensions, fileType: string | null }
) {
	const [searchedUserFiles, setSearchedUserFiles] = useState<FileInfo[]>([]);
	const [searchedUserFilesShowNull, setSearchedUserFilesShowNull] = useState<boolean>(false);
	const [searchedGlobalFiles, setSearchedGlobalFiles] = useState<SearchItem[]>([]);
	const [searchedGlobalFilesShowNull, setSearchedGlobalFilesShowNull] = useState<boolean>(false);
	const [loading, setLoading] = useState<boolean>(false);
	const [paginationLoading, setPaginationLoading] = useState<boolean>(false);
	const [showGlobalSearch, setShowGlobalSearch] = useState<boolean>(false);
	const queryClient = useQueryClient();
	const [errorMessage, setErrorMessage] = useState<string | null>(null);
	const [globalSearchErrorMessage, setGlobalSearchErrorMessage] = useState<string | null>(null);
	const t = useTranslations('Global');

	const [searchTotalPages, setSearchTotalPages] = useState<number>(0);
	const [searchCurrentPages, setSearchCurrentPages] = useState<number>(1);

	useImperativeHandle(ref, () => ({
		clearList: () => {
			setSearchedUserFiles([]);
			setSearchedGlobalFiles([]);
			setSearchedUserFilesShowNull(false);
			setSearchedGlobalFilesShowNull(false);
			setShowGlobalSearch(false);
			setSearchCurrentPages(1);
			setSearchTotalPages(0);
		}
	}));


	const handlerSearchUserFile = useCallback(async (fileId: string, page: number): Promise<void> => {
		setErrorMessage(null);
		setGlobalSearchErrorMessage(null);

		try {
			let result = await searchUserFiles(fileId);

			if (result.errorMessage) {
				throw result.errorMessage
			}

			if (result?.content?.length) {
				setSearchedUserFiles(result.content);

				const hasOwned = result?.content.some((item: { owner: boolean }) => {
					if (item.owner) {
						return true;
					}
					return false;
				});

				if (hasOwned) {
					if (fileType === 'image') {
						setShowGlobalSearch(true);
						handlerSearchGlobalFile(fileId, page);
					}
				}

			} else {
				setSearchedUserFilesShowNull(true);
				if (fileType === 'image') {
					setShowGlobalSearch(true);
					handlerSearchGlobalFile(fileId, page);
				}
			}
		} catch (error) {

			if (error === 'file-for-search-unsupported') {
				setErrorMessage(error);
			} else {
				setErrorMessage('search-error');
			}
		} finally {
			await queryClient.invalidateQueries({ queryKey: ['userData'] });
			await queryClient.invalidateQueries({ queryKey: ['userSearchData'] });
		}

	}, [fileId])

	const handlerSearchGlobalFile = useCallback(async (fileId: string, page: number, actionFromPagination?: boolean): Promise<void> => {
		setGlobalSearchErrorMessage(null);

		if (!actionFromPagination) {
			setLoading(true);
			setSearchedGlobalFilesShowNull(false);
			setSearchedGlobalFiles([]);
		} else {
			setPaginationLoading(true);
		}

		try {
			let result = await searchGlobalFiles(fileId, page);

			if (result.error) {
				throw result.error;
			}
			if (result.totalResults) {
				setSearchedGlobalFiles(result.images);
				setSearchTotalPages(result.totalPages);
				setSearchCurrentPages(page);

			} else {
				setSearchedGlobalFilesShowNull(true);
			}
		} catch (error) {
			if (error) {
				setGlobalSearchErrorMessage(error as string);
			} else {
				setGlobalSearchErrorMessage('error');
			}
		} finally {
/* 			await queryClient.invalidateQueries({ queryKey: ['userData'] });
			await queryClient.invalidateQueries({ queryKey: ['userSearchData'] }); */
			setLoading(false);
			setPaginationLoading(false);
		}

	}, [fileId])

	return (
		<>
			<div className="mb-4">
				<button
					className="btn btn-primary btn-search"
					disabled={!fileId}
					onClick={() => {
						if (fileId) {
							handlerSearchUserFile(fileId, 1)
						}
					}}
				>
					{t('start-search')}
				</button>

				{errorMessage && (
					<div className='mt-2 text-red-600 text-sm'>
						{t(errorMessage)}
					</div>
				)}
			</div>

			{(searchedUserFiles.length !== 0) && (
				<SearchedUserFilesList list={searchedUserFiles} allowedExtensions={allowedExtensions} />
			)}

			{searchedUserFilesShowNull && (
				<div className="user-file-search-results">
					<div className="results-header">
						<div className="results-title">{t('search-results-title')}</div>
						<div className="results-count">
							{t('files-found', { count: searchedUserFiles.length })}
						</div>
					</div>
					<div className="empty-results">
						<h3>{t('no-similar-files-title')}</h3>
						<p>{t('no-similar-files-description')}</p>
						<div className="empty-results-hint">
							<strong>{t('hint-title')}</strong> {t('hint-text')}
						</div>
					</div>
				</div>
			)}

			{showGlobalSearch && (
				<div className="global-search-section">
					<div className="global-search-header">
						<div className="global-search-title">
							{t('global-search-title')}
						</div>
						<div className="">
							{t('global-search-description')}
						</div>
						<div className="global-search-badge">
							{t('global-search-badge')}
						</div>
					</div>

					<div className="global-search-content">
						<div className="global-search-info">
							<div className="global-search-info-title">
								{t('global-search-info-title')}
							</div>
							<div className="global-search-info-text">
								{t('global-search-info-text')}
							</div>
						</div>

						<div className={`global-loading ${loading ? 'show' : ''}`} id="global-loading">
							<div className="global-spinner"></div>
							<div className="global-loading-text" id="global-loading-text">
								{t('searching-internet')}
							</div>
						</div>

						<div className={`global-result ${searchedGlobalFiles.length ? 'show' : ''}`} id="global-result">
							<div className="global-result-card">
								<div className="global-result-header">
									<span>{t('found-on-internet')}</span>
									{paginationLoading && (
										<div className="loading-animation">
											<span className="global-spinner"></span>
										</div>
									)}
								</div>
								<div className="global-result-content">
									<SearchedGlobalFilesList list={searchedGlobalFiles} />
								</div>
							</div>
						</div>

						{(searchedGlobalFilesShowNull && !loading) && (
							<div className="global-no-result" id="global-no-result">
								<h4>{t('no-similar-global-title')}</h4>
								<p className="global-no-result-text">
									{t('no-similar-global-description')}
								</p>
							</div>
						)}

						{globalSearchErrorMessage && (
							<>
								<div className="global-error">
									<strong>{t('search-error')}</strong>
								</div>
								<button
									onClick={() => {
										if (fileId) {
											handlerSearchGlobalFile(fileId, 1);
										}
									}}
									className="btn btn-primary btn-search"
								>
									{t('search-again')}
								</button>
							</>
						)}

						<Pagination
							totalPages={searchTotalPages}
							currentPage={searchCurrentPages}
							fileId={fileId}
							callBack={handlerSearchGlobalFile}
						/>
					</div>
				</div>
			)}
		</>
	);
}