'use client'

import { ViolationFileDetail } from '@/app/hooks/react-query/useFileViolations';
import { useEffect, useActionState, SetStateAction } from 'react';
import { fetchCaseInfo, createCase, MatchStatus } from '@/app/actions/violationActions';
import { useQuery } 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;
	created_at: string;
	updated_at: string;
	page_number: number;
	page_size: number;
	total_elements: number;
	total_pages: number;
	violation_id: 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, setLocalViolation }:
	{
		selectedViolation: ViolationFileDetail,
		updateStatusHandler: UpdateStatusHandler,
		setLocalViolation: React.Dispatch<SetStateAction<ViolationFileDetail>>
	}
) {
	const t = useTranslations('Global');
	const [state, formAction, isPending] = useActionState(createCase, undefined);

	const { data: caseInfo, isLoading: isLoadingCase } = useQuery({
		queryKey: ['caseInfo', selectedViolation.id],
		queryFn: () => fetchCaseInfo(selectedViolation.id),
		select: (data) => {
			if (data) {
				return data
			}
		},
		enabled: ENABLED_STATUSES.includes(selectedViolation.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);
		} 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]);

	if (!ENABLED_STATUSES.includes(selectedViolation.status)) {
		return (
			<div className="violation-info-case">
				<div className="note-form">
					<form action={formAction}>
						<input type="hidden" name="violationId" value={selectedViolation.id} />
						<div
							className="note-form-flex"
						>
							<section
								className="note-form-section"
							>
								<div
									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') + '...'}
										defaultValue={state?.previousCaseTitle ? state?.previousCaseTitle : ''}
									/>
								</div>

								{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-section"
							>
								<div
									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') + '...'}
										defaultValue={state?.previousAmount ? state?.previousAmount : ''}
									/>
								</div>

								{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-form-section"
						>
							<div
								className="note-form-group"
							>
								<label
									className="note-case-label"
									htmlFor="note"
								>
									{t('text-of-the-case')}
								</label>

								<textarea
									name="note"
									className="note-textarea"
									placeholder={t('fill-text-of-the-case') + '...'}
									defaultValue={state?.previousText ? state?.previousText : ''}
								>
								</textarea>
							</div>

							{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="button-actions"
						>
							<button
								type="submit"
								className="btn-s btn-primary-small"
								disabled={isPending}
							>
								{t('submit-violation')}
							</button>
						</div>
					</form>
				</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 ? (
					<>
						{caseInfo.body.content.map((item: CaseInfo) => {
							return (
								<div key={item.id}>
									<div className="complaint-details">
										<div className="complaint-details-item">
											<h5>{item.name}</h5>
										</div>

										<div className="complaint-details-item">
											<div className="complaint-details-title">
												{t('Status')}:
											</div>
											<div
												className="complaint-details-content"
											>
												{item.type}
											</div>
										</div>

										<div className="complaint-details-item">
											<div className="complaint-details-title">
												{t('date-of-creation')}:
											</div>
											<div
												className="complaint-details-content"
											>
												{item.created_at ? `${formatDate(item.created_at)}: ${formatDateTime(item.created_at)}` : '---'}
											</div>
										</div>

										<div className="complaint-details-item">
											<div className="complaint-details-title">
												{t('date-of-update')}:
											</div>
											<div
												className="complaint-details-content"
											>
												{item.updated_at ? `${formatDate(item.updated_at)}: ${formatDateTime(item.updated_at)}` : '---'}
											</div>
										</div>

										<div className="complaint-details-item">
											<div className="complaint-details-title">
												{t('amount-of-damage')}:
											</div>
											<div
												className="complaint-details-content"
											>
												{item.amount}
											</div>
										</div>

										<div className="complaint-details-item">
											<div className="complaint-details-title">
												{t('lawyer')}:
											</div>
											<div
												className="complaint-details-content"
											>
												{item.lawyer}
											</div>
										</div>
										<div className="complaint-details-item">
											<div className="complaint-details-title">
												{t('description')}:
											</div>
											<div
												className="complaint-details-content"
											>
												{item.description}
											</div>
										</div>
									</div>
								</div>
							);
						})}
					</>
				) : (
					<div>
						{t('no-information-about-the-complaint')}
					</div>
				)}
			</div>
		);
	}
}