import { Box, Button } from "@mui/material";
import { FC, useState } from "react";
import { useTranslation } from "react-i18next";

import { faultColor } from "@/constants";
import { AssetModel } from "@/contracts/client.schemas";
import { http } from "@/services/http.service";

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

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

interface UserLogRequest {
	assetId: string;
	message: string;
}

interface Props {
	asset: AssetModel;
}

export const EventActionsDialog: FC<Props> = ({ asset }) => {
	const [isLoading, setIsLoading] = useState(false);
	const { t } = useTranslation();
	const { post } = http;

	const saveLog = async (parameter: ActionParameter) => {
		const log: UserLogRequest = {
			assetId: parameter.assetId,
			message: parameter.comment,
		};

		await post("/api/logs", log);
	};

	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: asset.id,
			});

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

	return (
		<Box
			sx={{
				display: "flex",
				flexDirection: "column",
				gap: 2,
				width: "100%",
			}}
		>
			{items.map((item, index) => (
				<Button
					key={index}
					onClick={() => handleClick(item)}
					sx={{
						backgroundColor: item.color,
						color: "inherit",
					}}
					disabled={isLoading}
				>
					{item.title}
				</Button>
			))}
		</Box>
	);
};
