'use client'

import { useQuery } from '@tanstack/react-query';
import { getUserFilesData } from '@/app/actions/fileEntity';
import { useEffect, useState, useRef } from 'react';
import { FileTypeIcon } from '@/app/components/FileTypeIcon';
import { convertBytes } from '@/app/lib/convertBytes';
import { useTranslations } from 'next-intl';
import { useClickOutside } from '@/app/hooks/useClickOutside';
import Link from 'next/link';
import { getViolationFilesArray } from '@/app/actions/violationActions';
import { IconEye } from '@/app/ui/icons/icons';

interface ViolationFile {
	createdAt: string;
	fileId: string;
	fileName: string;
	fileSize: number;
	latestViolationDate: string;
	mimeType: string;
	status: string;
	supportId: number;
	violationCount: number;
}

export default function DashboardUserViolations() {
	const {
		data: violationData,
		isLoading,
		isError,
		error,
	} = useQuery<ViolationFile[]>({
		queryKey: ['violationData'],
		queryFn: () => getViolationFilesArray(),

		select: (data) => {
			return data?.slice(0, 5) || [];
		},
		/* refetchInterval: 30000 */
	});

	const t = useTranslations('Global');
	const formatDate = (timestamp: number | string) => {
		const date = new Date(timestamp);
		const day = date.getDate().toString().padStart(2, '0');
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const year = date.getFullYear();

		return `${day}.${month}.${year}`;
	};

	return (
		<div className="content-section">
			<div className="section-header">
				<h3 className="section-title">
					{t('violation')}
				</h3>
				<div
					className="section-add-file btn view-all-link"
				>
					<Link href='/pages/violations'>
						{t('all')}
					</Link>
				</div>
			</div>

			<div className="user-files-list">
				{isLoading && (
					<div
						className="loading-animation"
					>
						<div
							className="global-spinner"
						>
						</div>
					</div>
				)}

				{violationData?.length ? (
					violationData?.map((file) => {
						return (
							<div
								key={file.fileId}
								className="file-item"
							>
								<div className="file-icon violent">
									<Link
										href={`/pages/file/${file.fileId}`}
										className="bg-violet-500 hover:bg-violet-600"
										title={t('view')}
									>
										<IconEye />
									</Link>
								</div>
								<div className="file-info">
									<div className="file-name" title={file.fileName}>
										{file.fileName}
									</div>
									<div className="file-meta">
										{file.createdAt ? formatDate(file.createdAt) : 0} • {t('violations-found')}: {file.violationCount ? file.violationCount : 0}
									</div>
								</div>
							</div>
						)
					})
				) : (
					!isLoading && (
						<div>
							{t('there-are-no-files-yet')}
						</div>
					)
				)}
			</div>
		</div>
	)
}