import { toast } from "react-toastify";

import { AssetModel } from "@/contracts/client.schemas";
import { useMapMover } from "@/hooks/use-map-mover";
import { useWatcherStore } from "@/modules/watcher/store/watcher.store";

import { useAllAssetsCardContext } from "../contexts/useAllAssetsCardContext";
import { Divider } from "../Divider/Divider";

import styles from "./AssetView.module.css";

interface Props {
	asset: AssetModel;
	depth: number;
}

export function AssetView(props: Props) {
	const context = useAllAssetsCardContext();
	const isActive = context.activeAssetId === props.asset.id;
	const mapMover = useMapMover();
	const { setCurrentAssetId } = useWatcherStore();

	function handleClick() {
		if (isActive) {
			context.setActiveAssetId(undefined);
			return;
		}

		context.setActiveAssetId(props.asset.id);
		if (mapMover(props.asset.id)) {
			return;
		}

		toast.info("Объект не отмечен на карте");

		setCurrentAssetId(props.asset.id);
	}

	return (
		<>
			<div
				className={`${styles.container} ${isActive && styles.active} ${
					props.depth > 0 && styles.indent
				}`}
				onClick={handleClick}
			>
				<div className={styles.label} title={props.asset.name}>
					{props.asset.name}
				</div>
			</div>

			<Divider />
		</>
	);
}
