import { useState, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";
import { z } from "zod";

import { useSignalR } from "@/contexts/signalR/useSignalR";
import { UserLogModel } from "@/contracts/client.schemas";
import { useCreateLog, useGetLogList } from "@/contracts/logs";
import { useFormikWithZod } from "@/utils/useFormikWithZod";

type Props = {
	assetId: string;
};

export function OperatorCommentary(props: Props) {
	const { t } = useTranslation("translation");
	const api = useCreateLog();
	const signalR = useSignalR();
	const [logs, setLogs] = useState<UserLogModel[]>([]);
	const messagesEndRef = useRef<HTMLDivElement>(null);

	const {
		data: logsData,
		isLoading: loadingLogs,
		error: logsError,
	} = useGetLogList({
		AssetId: props.assetId,
		Take: 50,
	});

	useEffect(() => {
		if (logsData?.items) {
			setLogs(
				logsData.items.sort(
					(a, b) =>
						new Date(b.createdAt!).getTime() -
						new Date(a.createdAt!).getTime(),
				),
			);
		}
	}, [logsData]);

	useEffect(() => {
		if (messagesEndRef.current) {
			messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
		}
	}, [logs]);

	useEffect(() => {
		signalR.subscribe("LOGS.CREATED", (newLog: UserLogModel) => {
			if (newLog.assetId == props.assetId) {
				setLogs((prevLogs) =>
					[newLog, ...prevLogs].sort(
						(a, b) =>
							new Date(b.createdAt!).getTime() -
							new Date(a.createdAt!).getTime(),
					),
				);
			}
		});
	}, [signalR, props.assetId]);

	const LogSchema = z.object({
		message: z
			.string()
			.min(3, t("validation.minCountRequired", { count: 3 }))
			.max(100, t("validation.maxCountRequired", { count: 100 })),
	});

	const formik = useFormikWithZod({
		initialValues: {
			message: "",
		},
		validationSchema: LogSchema,
		validateOnMount: true,
		validateOnBlur: true,
		validateOnChange: true,
		onSubmit: async (values) => {
			try {
				await api.mutateAsync({
					data: {
						assetId: props.assetId,
						message: values.message,
					},
				});

				formik.resetForm();

				toast.success(t("success.commentaryCreated"));
			} catch (e) {
				console.error(e);
				toast.error(t("errors.failedToCreateLog"));
			}
		},
	});

	return (
		<div className="h-full flex flex-col gap-3 overflow-y-hidden">
			<form
				className="flex flex-col gap-1"
				onSubmit={formik.handleSubmit}
			>
				<label className="font-semibold">{t("commentary")}</label>
				<textarea
					className="p-3 border rounded-lg resize-none"
					rows={1}
					placeholder={t("extensionInformation")}
					value={formik.values.message}
					onChange={formik.handleChange}
					onBlur={formik.handleBlur}
					name="message"
				/>
				<button
					className="p-2 bg-[var(--primary-600)] text-[var(--white)] rounded-lg disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed"
					disabled={api.isPending || !formik.isValid}
					type="submit"
				>
					{t("add")}
				</button>
			</form>

			{/* Прокручиваемый список комментариев */}
			<div className="flex-1 overflow-y-hidden">
				<div className="h-full overflow-y-hidden flex flex-col">
					<h3 className="font-semibold mb-3 text-gray-800">
						Комментарии операторов
					</h3>
					<div className="h-full overflow-y-auto border border-gray-200 rounded-lg p-3 bg-gray-50">
						{loadingLogs ? (
							<div className="text-center text-gray-500">
								Загрузка комментариев...
							</div>
						) : logsError ? (
							<div className="text-center text-red-500">
								Ошибка загрузки комментариев
							</div>
						) : logs.length > 0 ? (
							logs.map((log, index) => (
								<div
									key={log.id || index}
									className="mb-3 p-3 bg-white rounded-md shadow-sm border-l-4 border-blue-500"
								>
									<div className="flex justify-between items-start mb-1">
										<span className="text-sm font-bold text-gray-900">
											{log.username ||
												"Оператор (ID: " +
													log.userId +
													")"}
										</span>
										<span className="text-xs text-gray-500">
											{new Date(
												log.createdAt!,
											).toLocaleString()}
										</span>
									</div>
									<p className="text-sm text-gray-700 ">
										{log.information}
									</p>
								</div>
							))
						) : (
							<div className="text-center text-gray-500">
								Нет комментариев
							</div>
						)}
						<div ref={messagesEndRef} />
					</div>
				</div>
			</div>
		</div>
	);
}
