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

import { useDialogStore } from "../../../contexts/dialog/lib/useDialogStore";
import { DialogDefaultHeader } from "../../../contexts/dialog/ui/DialogDefaultHeader";
import { useResetAlarms } from "../../../contracts/events";
import { useAudioStore } from "../../../features/AlarmPlayer/lib/audio.store";
import { http } from "../../../services/http.service";
import { DialogContent, InputField } from "../../../shared";
import { DialogTitle } from "../../../shared/Shadcn/ui/dialog";
import { useFormikWithZod } from "../../../utils/useFormikWithZod";
import { useWatcherStore } from "../store/watcher.store";

interface TranslateItem {
	language: string;
	value: string;
}
interface ReasonItem {
	id: string;
	organizationId: string;
	translates: TranslateItem[];
}

interface Form {
	comment: string;
}

export function AlarmResettingDialog() {
	const { t, i18n } = useTranslation();
	const dialog = useDialogStore();
	const resetAlarm = useResetAlarms();
	const { setIsPlaying } = useAudioStore();

	const assetId = useWatcherStore((s) => s.currentAssetId);
	if (!assetId) throw new Error("Current assetId is required");

	const [asset, setAsset] = useState<{
		id: string;
		organizationId: string;
	} | null>(null);
	const [reasons, setReasons] = useState<ReasonItem[]>([]);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		http.get<{ id: string; organizationId: string }>(
			`/api/assets/${assetId}`,
		)
			.then((res) => setAsset(res))
			.catch(() => toast.error(t("Ошибка загрузки данных объекта")));
	}, [assetId, t]);

	const getTranslatedText = (translates: TranslateItem[]) => {
		if (!translates || !Array.isArray(translates)) {
			return "";
		}
		const langCode = i18n.language.split("-")[0];
		const tr = translates.find((x) => x.language === langCode);
		if (tr) {
			return tr.value;
		}
		const trPartial = translates.find((x) =>
			x.language.startsWith(langCode),
		);
		if (trPartial) {
			return trPartial.value;
		}
		if (translates.length > 0) {
			return translates[0].value;
		}
		return "";
	};

	useEffect(() => {
		if (!asset) return;
		setLoading(true);
		const lang = i18n.language.split("-")[0];
		const url = new URL(
			"/api/alarm-reset-comments",
			window.location.origin,
		);
		url.searchParams.set("organizationId", asset.organizationId);
		url.searchParams.set("lang", lang);

		http.get<{ items: ReasonItem[]; total: number }>(
			url.pathname + url.search,
		)
			.then((res) => {
				setReasons(res.items);
			})
			.catch(() => {
				toast.error(t("Ошибка загрузки причин сброса тревоги"));
			})
			.finally(() => setLoading(false));
	}, [asset, t, i18n.language]);

	const {
		values,
		isValid,
		isSubmitting,
		handleSubmit,
		handleBlur,
		handleChange,
		setFieldValue,
	} = useFormikWithZod<Form>({
		initialValues: { comment: "" },
		validationSchema: z.object({
			comment: z.string().min(1, t("requiredField")),
		}),
		onSubmit: async ({ comment }) => {
			try {
				await resetAlarm.mutateAsync({
					data: { assetIdList: [assetId], message: comment },
				});
				setIsPlaying(false);
				dialog.back();
				dialog.push({
					key: "success-resetting-alarm",
					content: <div>{t("Alarm reset!")}</div>,
				});
			} catch (err) {
				toast.error((err as Error).message);
			}
		},
	});

	return (
		<DialogContent className="max-h-[85vh] flex flex-col">
			<DialogDefaultHeader />
			<DialogTitle className="text-2xl font-semibold text-center mb-2">
				{t("Выберите причину для сброса тревоги")}
			</DialogTitle>

			{loading || !asset ? (
				<div className="flex items-center justify-center py-12">
					<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"></div>
					<p className="ml-3 text-gray-600">{t("Загрузка…")}</p>
				</div>
			) : (
				<form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
					<div className="flex-1 overflow-y-auto pr-2 mb-4 space-y-2">
						{reasons.map((r) => {
							const translatedText = getTranslatedText(
								r.translates,
							);
							const isSelected = values.comment === translatedText;
							return (
								<button
									key={r.id}
									type="button"
									onClick={() =>
										setFieldValue("comment", translatedText)
									}
									disabled={isSubmitting}
									className={`w-full p-3 rounded-lg transition-all duration-200 text-left
										${isSelected 
											? "bg-red-50 border-2 border-red-500 shadow-md" 
											: "bg-gray-50 border-2 border-transparent hover:border-gray-300 hover:shadow-sm"
										}
										${isSubmitting ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}
									`}
								>
									<div className="flex items-center">
										<div className={`w-5 h-5 rounded-full border-2 mr-3 flex items-center justify-center
											${isSelected ? "border-red-500 bg-red-500" : "border-gray-300"}
										`}>
											{isSelected && (
												<svg className="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
													<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
												</svg>
											)}
										</div>
										<span className={`text-base ${isSelected ? "font-medium text-red-900" : "text-gray-700"}`}>
											{translatedText || "Нет перевода"}
										</span>
									</div>
								</button>
							);
						})}
					</div>

					<div className="border-t pt-4 space-y-4 bg-white">
						<InputField
							label={t("Another")}
							name="comment"
							placeholder={t("Enter")}
							disabled={isSubmitting}
							value={values.comment}
							onChange={handleChange}
							onBlur={handleBlur}
						/>

						<button
							type="submit"
							disabled={!isValid || isSubmitting}
							className="w-full py-3 bg-red-600 text-white rounded-lg font-medium 
								hover:bg-red-700 active:bg-red-800 
								disabled:opacity-50 disabled:cursor-not-allowed
								transition-colors duration-200 shadow-sm hover:shadow-md"
						>
							{isSubmitting ? (
								<div className="flex items-center justify-center">
									<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
									{t("Обработка...")}
								</div>
							) : (
								t("Reset alarm")
							)}
						</button>
					</div>
				</form>
			)}
		</DialogContent>
	);
}
