import { useEffect, useState } from "react";

import { ArrowDownIcon, CheckBox } from "@/shared";

import { AssetListView } from "../AssetListView/AssetListView";
import { useReportAssetListContext } from "../contexts/useReportAssetListContext";
import { Divider } from "../Divider/Divider";

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

const arrowDefaultColor = "var(--black-300)";

interface Props {
	label: string;
	id: string;
	depth: number;
}

export function GroupView(props: Props) {
	const context = useReportAssetListContext();
	const isActive = context.isActiveGroup(props.id);
	const [isSelected, setIsSelected] = useState(
		context.isSelectedGroup(props.id),
	);

	useEffect(() => {
		setIsSelected(context.isSelectedGroup(props.id));
	}, [context.selectedAssetIds, context.groups, context.assets]);

	function handleClick() {
		if (isActive) {
			context.deactivateGroup(props.id);
			return;
		}

		context.activateGroup(props.id);
	}

	function handleCheck() {
		if (isSelected === true) {
			context.unselectGroup(props.id);
		} else {
			context.selectGroup(props.id);
		}
	}

	function getChecked() {
		if (isSelected === true) {
			return "checked";
		} else if (isSelected === "indeterminate") {
			return "indeterminate";
		} else {
			return "unchecked";
		}
	}

	return (
		<>
			<div
				className={`${styles.container} ${
					props.depth > 0 && styles.indent
				}`}
			>
				<div className={styles.labelGroup}>
					<CheckBox state={getChecked()} onClick={handleCheck} />
					<div className={styles.label}>{props.label}</div>
				</div>

				<div className={styles.arrow} onClick={handleClick}>
					<ArrowDownIcon color={arrowDefaultColor} />
				</div>
			</div>

			<Divider />

			{isActive && (
				<AssetListView groupId={props.id} depth={props.depth} />
			)}
		</>
	);
}
