import { convertBytes } from '@/app/lib/convertBytes';
import { toast } from 'sonner';
import { useState, ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import ModalWindow from '@/app/components/modalWindow';
import { IconEye, IconDownload } from '@/app/ui/icons/icons';

export function SearchedUserFilesList({ list }: { list: any }) {
	const [isFileLoading, setIsFileLoading] = useState(false);
	const [openWindow, setOpenWindow] = useState<boolean>(false);
	const [openWindowChildren, setOpenWindowChildren] = useState<ReactNode>(null);
	const t = useTranslations('Global');

	const handlerDownload = async (fileId: string, fileName: string) => {
		setIsFileLoading(true);

		try {
			const response = await fetch(`/api/download/${fileId}`);

			if (!response.ok) {
				throw new Error(`error: ${response.status}`);
			}

			const blob = await response.blob();
			const url = window.URL.createObjectURL(blob);
			const a = document.createElement('a');
			a.href = url;
			a.download = fileName || `file-${fileId}`;
			document.body.appendChild(a);
			a.click();
			window.URL.revokeObjectURL(url);
			document.body.removeChild(a);
			toast.success(`${t('file-is-downloading')} - ${fileName}`);
		} catch (error) {
			toast.error(t('failed-to-download-file'))
		} finally {
			setIsFileLoading(false);
		}
	};

	const handlerViewfile = async (e: any) => {
		setOpenWindowChildren(() => {
			return (
				<div
					className="modal-window-view-file"
				>
					<div className="modal-window-view-file-header">
						<div
							className="modal-window-view-file-title"
						>
							{e.originalFileName}
						</div>
					</div>
					<div
						className="modal-window-view-file-content"
					>
						<div className="modal-window-view-file-content-wrapper">
							<div className="image-section">
								<div className="image-container">
									<img
										src={e.url ? e.url : '#'}
										alt="img"
									/>
								</div>
							</div>
							<div
								className="file-info-card"
							>
								<div className="info-header">
									<h4>Информация о файле</h4>
								</div>
								<div className="info-item">
									<span className="info-label">ID в системе:</span>
									<span className="info-value">
										{e.supportId ? e.supportId : '#'}
									</span>
								</div>
								<div className="info-item">
									<span className="info-label">Дата загрузки:</span>
									<span className="info-value">
										{e.uploadDate ? e.uploadDate : '#'}
									</span>
								</div>
								<div className="info-item">
									<span className="info-label">Размер файла:</span>
									<span className="info-value">
										{convertBytes(e.fileSize)}
									</span>
								</div>
								<div className="info-item">
									<span className="info-label">Статус защиты:</span>
									<span className="info-value">
										{e.status ? e.status : '#'}
									</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			)
		})
		setOpenWindow(true);
	};

	return (
		<>
			<div
				className="user-file-search-results"
			>
				<div className="results-header">
					<div className="results-title">Результаты поиска</div>
					<div className="results-count">
						Найдено файлов: {list.length}
					</div>
				</div>
				<div
					className="results-list"
				>
					{list.map((e: any, index: number) => {
						console.log(e);
						console.log(e.similarityLevel);
						if (e.similarityLevel !== 'DIFFERENT') {
							return (
								<div
									key={index}

								>
									<div className="result-item">
										<div className="result-header">
											<div className="result-preview">
												{e.url ? (
													<img src={e.url} alt="Preview" />
												) : (
													<div className="preview-fallback">
														<span>📄</span>
													</div>
												)}
											</div>
											<div className="result-info">
												<div className="result-filename" title={e.originalFileName}>
													{e.originalFileName}
												</div>
												<div className="result-details">
													Загружен: {e.uploadDate ? e.uploadDate : '#'} •
													Размер: {convertBytes(e.fileSize)}
												</div>
											</div>
											<div className="similarity-score">
												<div className="similarity-percentage">
													{e.similarityLevel}
												</div>
											</div>
										</div>

										<div className="result-badges">
											<span className={`badge ${e.status === 'PROTECTED' ? 'badge-protected' : 'badge-not-protected'}`}>
												{e.status}
											</span>
										</div>


										<div className="result-actions">
											<button
												className="btn btn-secondary gap-1"
												onClick={() => {
													handlerViewfile(e);
												}}
											>
												<IconEye />
												Просмотр
											</button>
											<button
												className="btn btn-success gap-1"
												disabled={isFileLoading}
												onClick={() => handlerDownload(e.fileId, e.originalFileName)}
											>
												<IconDownload />
												Скачать
											</button>
										</div>
									</div>
								</div>)
						}
					})}
				</div>
			</div>
			<ModalWindow children={openWindowChildren} state={openWindow} callBack={setOpenWindow} />
		</>

	)
}