import { Backdrop, CircularProgress } from "@mui/material";
import { FC, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";

import { faultColor } from "@/constants";
import { useCreateLog } from "@/contracts/logs";

interface ActionParameter {
	assetId: string;
	comment: string;
}

interface ActionItem {
	title: string;
	action: (parameter: ActionParameter) => Promise<void>;
	color: string;
}

interface Props {
	assetId: string;
}

export const AssetActions: FC<Props> = ({ assetId }) => {
	const [isLoading, setIsLoading] = useState(false);
	const { t } = useTranslation();
	const createLog = useCreateLog();

	const saveLog = async (parameter: ActionParameter) => {
		await createLog.mutateAsync({
			data: {
				assetId: parameter.assetId,
				message: parameter.comment,
			},
		});

		toast.success("Сообщение успешно отправлено");
	};

	const items: ActionItem[] = [
		{
			title: t("acceptanceForProcessing"),
			action: saveLog,
			color: faultColor,
		},
		{
			title: t("notifyingThoseResponsible"),
			action: saveLog,
			color: faultColor,
		},
		{
			title: t("observationOfAnObject"),
			action: saveLog,
			color: faultColor,
		},
		{
			title: t("callATechnician"),
			action: saveLog,
			color: faultColor,
		},
	];

	const handleClose = () => {
		// close(Dialogs.EVENT_ACTIONS_CARD);
	};

	const handleClick = async (item: ActionItem) => {
		try {
			setIsLoading(true);

			await item.action({
				comment: item.title,
				assetId: assetId,
			});

			handleClose();
		} finally {
			setIsLoading(false);
		}
	};

	if (createLog.isPending) {
		return (
			<Backdrop
				sx={(theme) => ({
					color: "#fff",
					zIndex: theme.zIndex.drawer + 1,
				})}
				open={true}
			>
				<CircularProgress color="inherit" />
			</Backdrop>
		);
	}

	return (
		<div className="flex flex-wrap gap-4">
			{items.map((item, index) => (
				<button
					key={index}
					onClick={() => handleClick(item)}
					className="w-[400px] h-[60px] rounded-lg px-4 py-3 bg-[var(--primary-600)] hover:bg-[var(--primary-800)] text-white font-inter text-base font-medium cursor-pointer grow"
					disabled={isLoading}
					type="button"
				>
					{item.title}
				</button>
			))}
		</div>
	);
};
