'use client'

import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { getViolationSearchStatus, startGlobalMonitoring } from '@/app/actions/violationActions';
import { useState } from 'react';
import ModalWindow from '@/app/components/ModalWindow';
import { toast } from 'sonner';

/* {
	taskId: "9647fcd6-cf9b-4503-b399-b8d53794cd49",
	userId: 1,
	searchType: "all_files",
	status: "PROCESSING",
	totalFiles: 2,
	processedFiles: 0,
	createdAt: "2026-03-13T05:21:39.850518",
	updatedAt: null
} */
interface violationSearchStatus {
	taskId?: string,
	userId?: number,
	searchType?: 'all_files' | 'monitoring',
	status: string,
	totalFiles?: number,
	processedFiles?: number,
	createdAt?: string,
	updatedAt?: null
}

export default function ViolationsCheckAllSection() {
	const {
		data: violationSearchStatus,
		isLoading,
		isError,
		error
	} = useQuery({
		queryKey: ['violationSearchStatus'],
		queryFn: () => {
			return getViolationSearchStatus();
		},
		select: (data: violationSearchStatus) => {
			console.log('violationSearchStatus');
			console.log(data);

			if (data) {
				return data;
			} else {
				return null
			}
		},
		refetchInterval: (query) => {
			const status = query.state.data?.status;
			if (status === 'PROCESSING') {
				return 10000;
			}

			return false;
		}
	});
	const queryClient = useQueryClient();
	const [isProcessing, setIsProcessing] = useState<boolean>(false);
	const [openWindow, setOpenWindow] = useState<boolean>(false);
	const t = useTranslations('Global');

	async function openModalWindow() {
		await queryClient.invalidateQueries({ queryKey: ['violationSearchStatus'] });
		setOpenWindow(true);
	}

	async function handlerStartMonitoring(type: 'monitoring' | 'all_files') {
		setIsProcessing(true);

		try {
			const response = await startGlobalMonitoring(type);
			if (response?.taskId) {
				toast.success(t('file-verification-started-successfully'));
				queryClient.invalidateQueries({ queryKey: ['violationSearchStatus'] });
			} else {
				throw 'error'
			}
		} catch (error) {
			toast.error(t('an-error-occurred-while-starting-file-verification'));
		} finally {
			setIsProcessing(false);
			setOpenWindow(false);
		}
	}

	function ConfirmationModal() {
		return (
			<div className="modal-window-confirm-payment">
				<h3 className="modal-window-confirm-payment-title">
					Поиск нарушений во всех ваших изображениях
				</h3>
				<div className="modal-window-confirm-payment-price">
					<div>Варианты проверки.</div>
				</div>
				<div className="flex justify-center gap-4">
					<button
						className="btn-primary btn-cancel"
						disabled={isProcessing}
						onClick={() => {
							handlerStartMonitoring('all_files');
						}}
					>
						Проверить все
					</button>
					<button
						className="btn-primary btn-cancel"
						disabled={isProcessing}
						onClick={() => {
							handlerStartMonitoring('monitoring');
						}}
					>
						Проверить файлы с мониторингом
					</button>
				</div>
			</div>
		);
	}

	return (
		<>
			<ModalWindow state={openWindow} callBack={setOpenWindow}>
				<ConfirmationModal />
			</ModalWindow>
			<div className="violation-check-all-section">

				<div className="check-all-left">
					<div className="check-all-header">
						{/* <div className="check-all-icon">🔍</div> */}
						<div className="check-all-title">Глобальная проверка контента</div>
					</div>
					<div className="check-all-description">
						Поиск нарушений во всех ваших изображениях. Проверка только точных совпадений (95%+).
					</div>
					{violationSearchStatus?.status && (
						<div>
							{violationSearchStatus?.status}
						</div>
					)}
				</div>
				<button
					type="button"
					className="check-all-btn"
					onClick={() => {
						openModalWindow()
					}}
				>
					Проверить все
				</button>
			</div>
		</>
	)
}