import { Button, Tooltip, LoadingOverlay } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { IconImageInPicture } from "@tabler/icons-react";
import { useState } from "react";
import { useImagesDetected } from "../../stores/use-images-detected";
import { convertToBoundingBox } from "../../ultils";
import { useHotkeys } from "@mantine/hooks";

export const SaveButton = ({ currentData, imageLabelRef, onSaved, disabled = false }) => {
	const [loading, setLoading] = useState(false);

	const { appendImageDetect, images } = useImagesDetected();

	const handleSave = async ({ blurredRegions, infoImage, imageName, listLabel }) => {
		try {
			if (blurredRegions?.length > 0) {
				let arrPoints = "";
				blurredRegions?.forEach((points) => {
					const img_w = infoImage?.width;
					const img_h = infoImage?.height;

					// Get bounding box
					const x_min = Math.min(...points.map((p) => p.x));
					const y_min = Math.min(...points.map((p) => p.y));
					const x_max = Math.max(...points.map((p) => p.x));
					const y_max = Math.max(...points.map((p) => p.y));

					const x_center = (x_min + x_max) / 2 / img_w;
					const y_center = (y_min + y_max) / 2 / img_h;
					const width = (x_max - x_min) / img_w;
					const height = (y_max - y_min) / img_h;

					// Get class ID
					const class_id = listLabel.find((label) => label?.name === points[0].label)?.id || "0";

					const yolo_label = `${class_id} ${x_center.toFixed(6)} ${y_center.toFixed(6)} ${width.toFixed(6)} ${height.toFixed(6)}`;

					arrPoints += yolo_label + "\n";
				});

				const url = `${process.env.REACT_APP_API_URL}/save`;
				// const url = `http://127.0.0.1:5000/save`;
				const formData = new FormData();
				formData.append("list", arrPoints);
				formData.append("imageName", imageName);
				setLoading(true);
				const response = await fetch(url, {
					method: "POST",
					body: formData,
				});

				const data = await response.json();

				if (data.success) {
					const newPoints = blurredRegions.map((points) => {
						return convertToBoundingBox(points);
					});

					currentData.points = newPoints;
					currentData["isSave"] = true;

					const newImages = images.map((image) => {
						if (image.image_name === imageName) {
							return {
								...image,
								points: newPoints,
								isSave: true,
							};
						}

						return { ...image };
					});

					appendImageDetect(newImages);

					notifications.show({
						title: "Save Success",
						message: `${imageName} save success`,
						color: "green",
					});

					if (onSaved) {
						onSaved({ ...currentData });
					}
				}
			}
		} catch (error) {
			notifications.show({
				title: "Save Error",
				message: error?.message || "Internal Server Error",
				color: "red",
			});
		} finally {
			setLoading(false);
		}
	};

	const handleSubmit = () => {
		const saveData = imageLabelRef.current?.getSaveData();

		if (!saveData) return;

		handleSave(saveData);
	};

	useHotkeys([["ctrl+S", handleSubmit]]);

	return (
		<Tooltip label={"Ctrl + S"}>
			<Button className="relative ư-f" disabled={!currentData || disabled} onClick={handleSubmit} leftSection={<IconImageInPicture size={14} />}>
				Save
				<LoadingOverlay visible={loading} loaderProps={{ size: 14 }} />
			</Button>
		</Tooltip>
	);
};
