'use client'

import { FileItem } from '@/app/components/tanstak-table/TanstakTable';
import { useEffect, useState, useRef } from 'react';
import { useTranslations } from 'next-intl';
import { useQueryClient } from '@tanstack/react-query';
import { createPortal } from 'react-dom';
import { setMonitoring } from '@/app/actions/monitoringActions';
import { toast } from 'sonner';

export function MonitoringDropDown({ file }: {
	file: FileItem
}) {
	const [isOpen, setIsOpen] = useState(false);
	const [currentMonitoringStatus, setCurrentMonitoringStatus] = useState(file.monitoring);
	const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0, width: 0 });

	const dropdownRef = useRef<HTMLDivElement>(null);
	const buttonRef = useRef<HTMLButtonElement>(null);

	const t = useTranslations('Monitoring-status');
	const queryClient = useQueryClient();

	useEffect(() => {
		if (!isOpen) return;

		const handleClick = (event: MouseEvent) => {
			if (!dropdownRef?.current) {
				return;
			}

			if (!buttonRef?.current) {
				return;
			}

			if (buttonRef?.current.contains(event.target as Node)) {
				return;
			}

			if (!dropdownRef.current.contains(event.target as Node)) {
				setIsOpen(false);
			}
		};

		document.addEventListener('mousedown', handleClick);
		return () => {
			document.removeEventListener('mousedown', handleClick);
		};
	}, [dropdownRef, setIsOpen, isOpen]);

/* 	useEffect(() => {
		if (file.monitoring) {
			setCurrentMonitoringStatus(file.monitoring ? file.monitoring : 'NONE');
		}
	}, [file.monitoring]); */

	useEffect(() => {
		if (isOpen && buttonRef.current) {
			const rect = buttonRef.current.getBoundingClientRect();
			setDropdownPosition({
				top: rect.bottom + window.scrollY,
				left: rect.left + window.scrollX,
				width: rect.width
			});
		}
	}, [isOpen]);

	async function clickHandler(monitoring: string) {

		const response = await setMonitoring(file.id, monitoring);

		if (response.success) {
			await queryClient.invalidateQueries({ queryKey: ['userFilesData'] });
			setIsOpen(false);
			toast.success(t('the-file-is monitored', { fileName: file.fileName }));
			setCurrentMonitoringStatus(monitoring);
		} else {
			toast.warning(t('failed-to-establish-monitoring'));
		}
	}

	return (
		<div className="dropdown-wrapper monitoring-dropdown">
			<button
				ref={buttonRef}
				onClick={() => {
					setIsOpen(!isOpen);
				}}
				className="dropdown-button"
			>
				<span className="flex items-center">
					<span className="mr-2">
						{t(currentMonitoringStatus)}
					</span>
				</span>
				<svg
					className={`w-5 h-5 ml-2 transition-transform ${isOpen ? 'rotate-180' : ''}`}
					xmlns="http://www.w3.org/2000/svg"
					viewBox="0 0 20 20"
					fill="currentColor"
				>
					<path
						fillRule="evenodd"
						d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
						clipRule="evenodd"
					/>
				</svg>
			</button>
			{isOpen && createPortal(
				<div
					className="dropdown-list-portal"
					ref={dropdownRef}
					style={{
						position: 'absolute',
						top: dropdownPosition.top,
						left: dropdownPosition.left,
						width: dropdownPosition.width,
						zIndex: 99999
					}}
				>
					<ul className="dropdown-list" role="listbox">
						<li
							className={`dropdown-item ${currentMonitoringStatus === 'NONE' ? 'current' : ''}`}
							onClick={() => {
								clickHandler('NONE')
							}}
						>
							{t('NONE')}
						</li>
						<li
							className={`dropdown-item ${currentMonitoringStatus === 'MONITORING_DAILY' ? 'current' : ''}`}
							onClick={() => {
								clickHandler('MONITORING_DAILY')
							}}
						>
							{t('MONITORING_DAILY')}
						</li>
						<li
							className={`dropdown-item ${currentMonitoringStatus === 'MONITORING_WEEKLY' ? 'current' : ''}`}
							onClick={() => {
								clickHandler('MONITORING_WEEKLY')
							}}
						>
							{t('MONITORING_WEEKLY')}
						</li>
						<li
							className={`dropdown-item ${currentMonitoringStatus === 'MONITORING_MONTHLY' ? 'current' : ''}`}
							onClick={() => {
								clickHandler('MONITORING_MONTHLY')
							}}
						>
							{t('MONITORING_MONTHLY')}
						</li>
					</ul>
				</div>,
				document.body
			)}
		</div>
	)
}