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

import { useSignalR } from "@/contexts/signalR/useSignalR";
import { ResponsiblePersonModel } from "@/contracts/client.schemas";
import { useGetResponsiblePersonList } from "@/contracts/responsible-persons";
import {
	CREATED_NOTIFICATION,
	DELETED_NOTIFICATION,
	UPDATED_NOTIFICATION,
} from "@/enums/notifications.enum";

export const useResponsiblePersons = ({
	assetIdString,
}: {
	assetIdString: string;
}): {
	responsiblePersons: ResponsiblePersonModel[];
	isLoading: boolean;
	isError: boolean;
	error: string;
} => {
	const { t } = useTranslation("translation");

	const { data, isLoading, error, isError } = useGetResponsiblePersonList({
		AssetId: assetIdString,
	});
	const [responsiblePersons, setResponsiblePersons] = useState<
		ResponsiblePersonModel[]
	>(data?.items ?? []);

	useEffect(() => {
		setResponsiblePersons(data?.items ?? []);
	}, [data]);

	const { subscribe, unsubscribe } = useSignalR();
	useEffect(() => {
		subscribe(`$RESPONSIBLE-PERSONS.${CREATED_NOTIFICATION}`, onCreated);
		subscribe(`$RESPONSIBLE-PERSONS.${UPDATED_NOTIFICATION}`, onUpdated);
		subscribe(`$RESPONSIBLE-PERSONS.${DELETED_NOTIFICATION}`, onDeleted);

		return () => {
			unsubscribe(
				`$RESPONSIBLE-PERSONS.${CREATED_NOTIFICATION}`,
				onCreated,
			);
			unsubscribe(
				`$RESPONSIBLE-PERSONS.${UPDATED_NOTIFICATION}`,
				onUpdated,
			);
			unsubscribe(
				`$RESPONSIBLE-PERSONS.${DELETED_NOTIFICATION}`,
				onDeleted,
			);
		};
	}, []);

	function onCreated(entity: any): void {
		if (entity.assetId !== assetIdString) {
			return;
		}

		setResponsiblePersons((prev) => [...prev, entity]);

		toast.success(t("Responsible person created"));
	}

	function onUpdated(entity: any): void {
		if (entity.assetId !== assetIdString) {
			return;
		}

		const index = responsiblePersons.findIndex((x) => x.id === entity.id);
		if (index !== -1) {
			responsiblePersons[index] = entity;
			setResponsiblePersons([...responsiblePersons]);
		}
	}

	function onDeleted(entity: any): void {
		if (entity.assetId !== assetIdString) {
			return;
		}

		setResponsiblePersons((prev) => prev.filter((x) => x.id !== entity.id));

		toast.success(t("Responsible person deleted"));
	}

	return {
		responsiblePersons,
		isLoading,
		isError,
		error: error as string,
	};
};
