import { Cancel, Search } from "@mui/icons-material";
import {
	Box,
	IconButton,
	Paper,
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableHead,
	TableRow,
	TextField,
	Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { AssetModel } from "@/contracts/client.schemas";

import { useWatcher } from "../hooks/useWatcher";
import { useWatcherStore } from "../store/watcher.store";

const searchInitializeValues = {
	searchTerm: "",
};

export const EventObjectTable: FC = () => {
	const { t } = useTranslation();
	const watcher = useWatcher();
	const { assets, currentAssetId } = useWatcherStore();
	const [visibleAssets, setVisibleAssets] = useState<string[]>([]);

	useEffect(() => {
		submitForm();
	}, [assets]);

	const {
		values,
		handleSubmit,
		handleBlur,
		handleChange,
		resetForm,
		submitForm,
	} = useFormik({
		initialValues: searchInitializeValues,
		onSubmit: ({ searchTerm }) => {
			const lowerFilter = searchTerm.trim().toLowerCase();

			if (!lowerFilter) {
				setVisibleAssets(watcher.alarmedAssets.map((x) => x.id));
				return;
			}

			setVisibleAssets(
				assets
					.filter((asset) =>
						asset.name.toLowerCase().includes(lowerFilter),
					)
					.map((x) => x.id),
			);
		},
	});

	const handleClearSearchTerm = () => {
		resetForm();
		submitForm();
	};

	const handleRowClick = (asset: AssetModel) => {
		watcher.selectAsset(asset.id);
	};

	const viewAssets = assets.filter((x) => visibleAssets.includes(x.id));

	return (
		<Box
			sx={{
				display: "flex",
				flexDirection: "column",
				gap: 3,
				width: "100%",
				alignItems: "stretch",
			}}
		>
			<Box
				sx={{
					display: "flex",
					alignItems: "center",
					justifyContent: "stretch",
					width: "100%",
				}}
			>
				<form onSubmit={handleSubmit} className="w-100 pt-2">
					<TextField
						label={t("searchAnObjectByName")}
						fullWidth
						variant="outlined"
						name="searchTerm"
						value={values.searchTerm}
						onBlur={handleBlur}
						onChange={handleChange}
						slotProps={{
							input: {
								endAdornment: (
									<>
										<IconButton
											type="button"
											onClick={handleClearSearchTerm}
										>
											<Cancel fontSize="inherit" />
										</IconButton>
										<IconButton type="submit">
											<Search fontSize="inherit" />
										</IconButton>
									</>
								),
							},
						}}
					/>
				</form>
			</Box>

			<Box
				sx={{
					width: "100%",
					height: "100%",
					overflow: "hidden",
					flexGrow: 1,
				}}
				component={Paper}
			>
				<TableContainer sx={{ maxHeight: "25rem" }}>
					<Table stickyHeader size="small">
						<TableHead>
							<TableRow>
								<TableCell>{t("assetName")}</TableCell>
							</TableRow>
						</TableHead>
						<TableBody>
							{viewAssets.map((asset) => (
								<TableRow
									key={asset.id}
									selected={currentAssetId === asset.id}
									onClick={() => handleRowClick(asset)}
									style={{
										backgroundColor:
											currentAssetId === asset.id
												? "#88b"
												: "inherit",
									}}
								>
									<TableCell>
										<Typography
											variant="body2"
											sx={{
												whiteSpace: "nowrap",
												overflow: "hidden",
												textOverflow: "ellipsis",
											}}
										>
											{asset.name}
										</Typography>
									</TableCell>
								</TableRow>
							))}
						</TableBody>
					</Table>
				</TableContainer>
			</Box>
		</Box>
	);
};
