import { Stack } from "@mui/material";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

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

import { filterAssets } from "../lib/filterAssets";

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

interface Props {
	onExpand: () => void;
	onCollapse: () => void;
}

export function AssetSearchBox(props: Props) {
	const [searchTerm, setSearchTerm] = useState("");
	const assets = useWatcherStore((x) => x.assets);
	const setCurrentAssetId = useWatcherStore((x) => x.setCurrentAssetId);
	const [assetList, setAssetList] = useState<
		{ item: AssetModel; index: number }[]
	>([]);
	const { t } = useTranslation("translation");
	const mapMover = useMapMover();

	useEffect(() => {
		if (!searchTerm) {
			setAssetList([]);
			return;
		}

		const assetList = filterAssets(assets, searchTerm);
		setAssetList(assetList);
	}, [searchTerm, assets]);

	useEffect(() => {
		if (assetList.length > 0) {
			props.onExpand();
		} else {
			props.onCollapse();
		}
	}, [assetList]);

	function openAssetCard(asset: AssetModel) {
		setCurrentAssetId(asset.id);

		if (mapMover(asset.id)) {
			return;
		}

		setSearchTerm("");
	}

	return (
		<Stack className="w-100">
			<SearchBox
				onSearch={setSearchTerm}
				label={t("Search")}
				search={searchTerm}
			/>
			<ul className={styles.list} onScroll={(e) => e.stopPropagation()}>
				{assetList.map((asset) => (
					<li
						key={asset.item.id}
						onClick={() => openAssetCard(asset.item)}
					>
						{asset.index !== 0 &&
							asset.item.name.substring(0, asset.index)}
						<b>
							{asset.item.name.substring(
								asset.index,
								asset.index + searchTerm.length,
							)}
						</b>
						{asset.item.name.substring(
							asset.index + searchTerm.length,
						)}
					</li>
				))}
			</ul>
		</Stack>
	);
}
