import { ComponentType, ReactNode, useState } from "react";

import { AlertIcon, ButtonGroup, Icon, MenuIcon, ReportIcon } from "@/shared";

import styles from "./AssetActions.module.css";
import { AllAssetsCard, AlarmAssetsCard, ReportAssetList } from "./cards";

type ModuleKey = "all" | "alarm" | "report";
interface Module {
	key: ModuleKey;
	titleKey: string;
	onClick: () => void;
	Icon: ComponentType<Icon>;
	color: string;
	card: ReactNode;
}

export function AssetActions() {
	const [currentModule, setCurrentModule] = useState<ModuleKey>();

	function allAssets() {
		setCurrentModule(currentModule === "all" ? undefined : "all");
	}

	function alarmAssets() {
		setCurrentModule(currentModule === "alarm" ? undefined : "alarm");
	}

	function reports() {
		setCurrentModule(currentModule === "report" ? undefined : "report");
	}

	const modules: Module[] = [
		{
			key: "all",
			titleKey: "All assets",
			onClick: allAssets,
			Icon: MenuIcon,
			color: "var(--black-300)",
			card: <AllAssetsCard />,
		},
		{
			key: "alarm",
			titleKey: "Alarm assets",
			onClick: alarmAssets,
			Icon: AlertIcon,
			color: "var(--black-300)",
			card: <AlarmAssetsCard />,
		},
		{
			key: "report",
			titleKey: "Reports",
			onClick: reports,
			Icon: ReportIcon,
			color: "var(--black-300)",
			card: <ReportAssetList />,
		},
	];

	function renderModule(moduleKey?: ModuleKey) {
		if (!moduleKey) {
			return null;
		}

		const moduleRender = modules.find((x) => x.key === moduleKey)?.card;
		if (!moduleRender) {
			throw new Error("Module not found");
		}

		return moduleRender;
	}

	function getActiveIndex() {
		return modules.findIndex((x) => x.key === currentModule);
	}

	return (
		<div className={styles.stack}>
			<ButtonGroup items={modules} activeIndex={getActiveIndex()} />

			{currentModule && (
				<div className={styles.cardContainer}>
					{renderModule(currentModule)}
				</div>
			)}
		</div>
	);
}
