'use client'

import { ViolationFileDetail } from '@/app/hooks/react-query/useFileViolations';
import { useActionState, useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { createComplaint, fetchComplainInfo } from '@/app/actions/violationActions';
import { toast } from 'sonner';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { MatchStatus } from '@/app/actions/violationActions';

interface complaintInfo {
	id: number,
	status: string,
	complaint_text: string,
	violation_id: number,
	email: string,
	created_at: string,
	updated_at: string,
	not_moderated: boolean
}

const ENABLED_STATUSES = ['COMPLAINT_IN_WORK', 'COMPLAINT_AND_LEGAL_IN_WORK'];
type UpdateStatusHandler = (id: number, status: MatchStatus) => Promise<boolean>;

export default function CaseComplaint({ selectedViolation, updateStatusHandler }: { selectedViolation: ViolationFileDetail, updateStatusHandler: UpdateStatusHandler }) {
	const t = useTranslations('Global');
	const queryClient = useQueryClient();

	const [showCreateCase, setShowCreateCase] = useState(false);
	const [localViolation, setLocalViolation] = useState<ViolationFileDetail>(selectedViolation);
	const [state, formAction, isPending] = useActionState(createComplaint, undefined);

	useEffect(() => {
		setLocalViolation(selectedViolation);
	}, [selectedViolation]);

	const { data: complainInfo, isLoading: isLoadingComplain } = useQuery({
		queryKey: ['complainInfo', localViolation.id],
		queryFn: () => fetchComplainInfo(localViolation.id),
		select: (data) => {
			if (data) {
				return data
			}
		},
		enabled: ENABLED_STATUSES.includes(localViolation.status),
	});

	useEffect(() => {
		if (state?.success) {
			toast.success(t('the-complaint-has-been-registered'));

			const newStatus = selectedViolation.status === 'LEGAL_IN_WORK'
				? 'COMPLAINT_AND_LEGAL_IN_WORK'
				: 'COMPLAINT_IN_WORK';

			setLocalViolation(prev => ({
				...prev,
				status: newStatus
			}));

			updateStatusHandler(selectedViolation.id, newStatus);

			setShowCreateCase(false);
		} else if (state && !state.success) {
			console.log(state.errorMessage);
			if (state.errorMessage?.server) {
				toast.warning(t(state.errorMessage.server));
			} else {
				toast.warning(t('the-complaint-has-not-been-registered'));
			}
		}
	}, [state, updateStatusHandler, selectedViolation.id]);

	function toggleForm() {
		setShowCreateCase(!showCreateCase);
	}

	if (!ENABLED_STATUSES.includes(localViolation.status)) {
		return (
			<div className="violation-info-case">
				{!showCreateCase ? (
					<button
						type="button"
						className="btn-action btn-case"
						onClick={toggleForm}
					>
						{t('filing-complaint')}
					</button>
				) : (
					<div>
						<button
							type="button"
							className="btn-action btn-case"
							onClick={toggleForm}
						>
							{t('cancel')}
						</button>

						<div className="note-form">
							<form action={formAction}>
								<input type="hidden" name="violationId" value={localViolation.id} />
								<textarea
									name="note"
									className="note-textarea"
									placeholder={`${t('text-of-the-complaint')}...`}>
								</textarea>
								<div
									className="flex gap-3"
								>
									<button
										type="submit"
										className="btn-small btn-primary-small"
										disabled={isPending}
									>
										{t('submit-violation')}
									</button>

									{state?.errorMessage?.textArea && (
										<p
											className="text-sm text-red-500"
										>

											{
												state?.errorMessage?.textArea.split('&').map((e, index) => {
													return (
														<span key={index}>
															{t(e)}
															<br />
														</span>
													)
												})
											}
										</p>
									)}
								</div>
							</form>
						</div>
					</div>
				)}
			</div>
		);
	} else {
		if (isLoadingComplain) {
			return (
				<div className="violation-info-case">
					<div
						className="loading-animation"
					>
						<div
							className="global-spinner large"
						>
						</div>
					</div>
				</div>
			);
		}

		return (
			<div className="violation-info-case">
				{complainInfo?.body.content ? (
					<div>
						{complainInfo.body.content.map((item: complaintInfo) => {
							return (
								<div key={item.id}>
									<h3 className="mb-3">
										{t('complaint-Information')}
									</h3>
									<div className="complaint-details">
										<p><strong>ID:</strong> {item.id}</p>
										<p><strong>{t('status')}:</strong> {item.status}</p>
										<p><strong>{t('text-of-the-complaint')}:</strong> {item.complaint_text}</p>
										<p><strong>{t('violation-id')}:</strong> {item.violation_id}</p>
										<p><strong>{t('email')}:</strong> {item.email}</p>
										<p><strong>{t('date-of-creation')}:</strong> {item.created_at}</p>
										<p><strong>{t('date-of-update')}:</strong> {item.updated_at}</p>
									</div>
								</div>
							);
						})}
					</div>
				) : (
					<div>
						{t('no-information-about-the-complaint')}
					</div>
				)}
			</div>
		);
	}
}