'use client'

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

interface CaseInfo {
	id: number;
	name: string;
	description: string;
	amount: number;
	priority: string;
	type: string;
	lawyer: string | null;
	createdAt: string;
	updatedAt: string;
	pageNumber: number;
	pageSize: number;
	totalElements: number;
	totalPages: number;
	violationId: number;
	content: string | null;
}

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

export default function CaseViolation({ 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(createCase, undefined);

	const { data: caseInfo, isLoading: isLoadingCase } = useQuery({
		queryKey: ['caseInfo', localViolation.id],
		queryFn: () => fetchCaseInfo(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 === 'COMPLAINT_IN_WORK'
				? 'COMPLAINT_AND_LEGAL_IN_WORK'
				: 'LEGAL_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('create-case')}
					</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} />
								<div
									className="note-form-flex"
								>
									<section
										className="note-form-group"
									>
										<label
											className="note-case-label"
											htmlFor="caseTitle"
										>
											{t('case-name')}
										</label>
										<input
											type="text"
											name="caseTitle"
											className="note-case-input"
											placeholder={t('fill-title-of-the-case') + '...'}
										/>
										{state?.errorMessage?.caseTitle && (
											<p
												className="text-sm text-red-500"
											>
												{
													state?.errorMessage?.caseTitle.split('&').map((e, index) => {
														return (
															<span key={index}>
																{t(e)}
																<br />
															</span>
														)
													})
												}
											</p>
										)}
									</section>
									<section
										className="note-form-group"
									>
										<label
											className="note-case-label"
											htmlFor="amount"
										>
											{t('amount-of-damage')}
										</label>
										<input
											type="number"
											name="amount"
											className="note-case-input"
											placeholder={t('enter-the-amount-of-damage') + '...'}
										/>
										{state?.errorMessage?.amount && (
											<p
												className="text-sm text-red-500"
											>
												{
													state?.errorMessage?.amount.split('&').map((e, index) => {
														return (
															<span key={index}>
																{t(e)}
																<br />
															</span>
														)
													})
												}
											</p>
										)}
									</section>
								</div>

								<section
									className="note-textarea-wrapper"
								>
									<textarea
										name="note"
										className="note-textarea"
										placeholder={t('fill-text-of-the-case') + '...'}
									>
									</textarea>
									{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>
									)}
								</section>
								<div
									className="flex gap-3"
								>
									<button
										type="submit"
										className="btn-small btn-primary-small"
										disabled={isPending}
									>
										{t('submit-violation')}
									</button>
								</div>
							</form>
						</div>
					</div>
				)}
			</div>
		);
	} else {
		if (isLoadingCase) {
			return (
				<div className="violation-info-case">
					<div
						className="loading-animation"
					>
						<div
							className="global-spinner large"
						>
						</div>
					</div>

				</div>
			);
		}

		return (
			<div className="violation-info-case">
				{caseInfo?.body?.content ? (
					<div>
						{caseInfo.body.content.map((item: CaseInfo) => {
							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('name')}:</strong> {item.name}</p>
										<p><strong>{t('description')}:</strong> {item.description}</p>
										<p><strong>{t('amount')}:</strong> {item.amount}</p>
										<p><strong>{t('priority')}:</strong> {item.priority}</p>
										<p><strong>{t('type')}:</strong> {item.type}</p>
										<p><strong>{t('lawyer')}:</strong> {item.lawyer || t('not-assigned')}</p>
										<p><strong>{t('violation-id')}:</strong> {item.violationId}</p>
										<p><strong>{t('date-of-creation')}:</strong> {item.createdAt ? `${formatDate(item.createdAt)}: ${formatDateTime(item.createdAt)}` : '---'}</p>
										<p><strong>{t('date-of-update')}:</strong> {item.createdAt ? `${formatDate(item.createdAt)}: ${formatDateTime(item.createdAt)}` : '---'}</p>
										{item.content && <p><strong>{t('content')}:</strong> {item.content}</p>}
									</div>
								</div>
							);
						})}
					</div>
				) : (
					<div>
						{t('no-information-about-the-complaint')}
					</div>
				)}
			</div>
		);
	}
}