'use client'

import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import { useState } from 'react';
import FilePageViolationInfo from '@/app/ui/file-page/violation-table/file-page-violation-info';
import { useFileViolations } from '@/app/hooks/react-query/useFileViolations';
import { ViolationFileDetail } from '@/app/hooks/react-query/useFileViolations';
import DropDownList from '@/app/components/DropDownList';
import { IconArrowLeft, IconArrowRight } from '@/app/ui/icons/icons';

export default function FilePageViolationsList({
	currentPage,
	fileId,
	status
}: {
	currentPage: number,
	fileId: string,
	status: string | undefined
}) {
	const t = useTranslations('Global');
	const tStatus = useTranslations('Match-status');
	const router = useRouter();
	const pathname = usePathname();
	const searchParams = useSearchParams();
	const [selectedViolation, setSelectedViolation] = useState<ViolationFileDetail | null>(null);

	const { data: fileViolations } = useFileViolations(fileId, currentPage, status);

	if (!fileViolations?.violations) {
		return null;
	}

	const handlePageChange = (page: number) => {
		const params = new URLSearchParams(searchParams);
		params.set('page', page.toString());
		router.push(`${pathname}?${params.toString()}`, { scroll: false });
	};

	const handleStatusChange = (status: string) => {
		const params = new URLSearchParams(searchParams);
		if (status) {
			params.set('status', status);
		} else {
			params.delete('status');
		}
		setSelectedViolation(null);
		params.set('page', '1');
		router.push(`${pathname}?${params.toString()}`, { scroll: false });
	};

	const getPageNumbers = () => {
		const pages = [];
		const maxVisible = 5;
		const total = fileViolations.total_pages;

		let start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
		let end = Math.min(total, start + maxVisible - 1);

		if (end - start + 1 < maxVisible) {
			start = Math.max(1, end - maxVisible + 1);
		}

		for (let i = start; i <= end; i++) {
			pages.push(i);
		}

		return pages;
	};

	function selectHandler(violation: ViolationFileDetail) {
		setSelectedViolation(violation);
	}

	return (
		<div className="block-wrapper">
			<div className="card-header">
				<h3 className="card-title">
					{t('all-file-violations')}
				</h3>

				<div className="flex items-center gap-4">
					<div
						className="status-filter-select"
					>
						<DropDownList
							value={status ? tStatus(status) : t('all-statuses')}
							callBack={handleStatusChange}
						>
							<li value=''>{t('all-statuses')}</li>
							<li value="NEW">{tStatus('NEW')}</li>
							<li value="SHOWED">{tStatus('SHOWED')}</li>
							<li value="LEGAL_IN_WORK">{tStatus('LEGAL_IN_WORK')}</li>
							<li value="COMPLAINT_IN_WORK">{tStatus('COMPLAINT_IN_WORK')}</li>
							<li value="COMPLAINT_AND_LEGAL_IN_WORK">{tStatus('COMPLAINT_AND_LEGAL_IN_WORK')}</li>
							<li value="AUTHORIZED_USE">{tStatus('AUTHORIZED_USE')}</li>
						</DropDownList>
					</div>
				</div>

			</div>

			<div
				className="sources-list-wrapper"
			>
				<div className="sources-list">
					{fileViolations.violations.map(item => {
						return (
							<div
								className={`source-card ${selectedViolation?.id === item.id ? 'selected' : ''}`}
								key={item.id}
								onClick={() => {
									selectHandler(item);
								}}
							>
								<div
									className="source-header-left"
								>
									<div className="source-image">
										<img src={item.url} alt="" />
									</div>
									<div>
										<span
											className="source-meta"
										>
											{t('source')}:
										</span>
										<span className="source-url">
											{item.host}
										</span>
									</div>
								</div>

								<div
									className="source-header-right"
								>
									{item.status === "COMPLAINT_AND_LEGAL_IN_WORK" ? (
										<>
											<span className="source-status legal_in_work">
												{tStatus('LEGAL_IN_WORK')}
											</span>
											<span className="source-status complaint_in_work">
												{tStatus('COMPLAINT_IN_WORK')}
											</span>
										</>
									) : (
										<span className={`source-status ${item.status.toLowerCase()}`}>
											{tStatus(item.status)}
										</span>
									)}

									<div className="source-actions">
										<Link
											href={item.page_url}
											className="btn-small btn-primary-small"
											target="_blank"
											scroll={false}
										>
											{t('open')}
										</Link>
									</div>
								</div>


							</div>
						);
					})}
				</div>
				{/* general info for match */}
				<FilePageViolationInfo selectedViolation={selectedViolation} />

			</div>
			<div
				className="sources-list-pagination"
			>
				<span>
					{t('total-violations')}: {fileViolations.total_elements} | {t('page')} {fileViolations.current_page} {t('out-of')} {fileViolations.total_pages}
				</span>
				{fileViolations.total_pages > 1 && (
					<div className="pagination-controls">
						<button
							onClick={() => handlePageChange(currentPage - 1)}
							className="arrow"
							disabled={!fileViolations.has_previous}
						>
							<IconArrowLeft />
						</button>

						<div
							className="pagination-controls-pages"
						>
							{getPageNumbers().map(pageNum => (
								<button
									key={pageNum}
									onClick={() => handlePageChange(pageNum)}
									/* className={`pagination-item ${currentPage === pageNum ? 'pagination-item-active' : ''}`} */
									className={currentPage === pageNum ? 'current' : 'other'}
								>
									{pageNum}
								</button>
							))}
						</div>


						<button
							onClick={() => handlePageChange(currentPage + 1)}
							className="arrow"
							disabled={!fileViolations.has_next}
						>
							<IconArrowRight />
						</button>
					</div>
				)}
			</div>
		</div>
	);
}