import { useCallback, useEffect, useState } from "react";
import axios from "axios";
import { AssetIdSetter } from "./AssetIdSetter";
import { Filter, FilterValues } from "./Filter";
import { AssetMap } from "./models/AssetMap";
import { CreateMapCard } from "./CreateMapCard";
import { useAssetMap } from "./hooks/useAssetMap";

export function AssetMapsTable() {
	const [rows, setRows] = useState<AssetMap[]>([]);
	const [visibleRows, setVisibleRows] = useState<AssetMap[]>([]);
	const [updateCardAssetMap, setUpdateCardAssetMap] = useState<AssetMap>();
	const [filter, setFilter] = useState<FilterValues>({
		useOnlyEmptyAssetId: false,
	});
	const [isLoading, setIsLoading] = useState(false);
	const [imeiFilter, setImeiFilter] = useState("");
	const [isOpenedCreatingCard, setIsOpenedCreatingCard] = useState(false);
	const assetMapRepository = useAssetMap();

	const update = useCallback(() => {
		setIsLoading(true);
		axios
			.get("/api/asset-maps", { params: filter })
			.then((response) => {
				setRows(response.data.items);
			})
			.catch((error) => console.error(error))
			.finally(() => setIsLoading(false));
	}, [filter]);

	useEffect(() => {
		update();
	}, [filter, update]);

	useEffect(() => {

	}, [updateCardAssetMap]);

	useEffect(() => {
		if (!imeiFilter) {
			return setVisibleRows(rows);
		}

		const filteredRows = rows.filter((row) => row.abonent?.includes(imeiFilter));
		setVisibleRows(filteredRows);
	}, [rows, imeiFilter]);

	const openCard = (assetMap: AssetMap) => {
		setUpdateCardAssetMap(assetMap);
	};

	const closeCard = () => {
		setUpdateCardAssetMap(undefined);
		update();
	};

	function openCreatingCard(): void {
		setIsOpenedCreatingCard(true);
	}

	function tryDelete(row: AssetMap): void {
		assetMapRepository.remove(row.id)
			.then(() => update());
    }

	return (
		<div className="container d-flex flex-column gap-3">
			<h1>Переходы из объектных ИД в Мониторинг</h1>

			{!isOpenedCreatingCard && <button
				className="btn btn-primary d-flex align-items-center gap-2 justify-content-center"
				onClick={openCreatingCard}
				disabled={isLoading}
			>
				Добавить вручную
				{isLoading && (
					<span className="spinner-border spinner-border-sm"></span>
				)}
			</button>
			}

			{
				isOpenedCreatingCard && (
					<div>
						<CreateMapCard
							onClose={() => setIsOpenedCreatingCard(false)}
							requireUpdate={update} />
					</div>
				)
			}

			{updateCardAssetMap && (
				<div>
					<AssetIdSetter assetMap={updateCardAssetMap} onClose={closeCard} />
				</div>
			)}

			<button
				className="btn btn-secondary d-flex align-items-center gap-2 justify-content-center"
				onClick={update}
				disabled={isLoading}
			>
				Обновить
				{isLoading && (
					<span className="spinner-border spinner-border-sm"></span>
				)}
			</button>

			{/* Filter */}
			<Filter onChange={setFilter} isLoading={isLoading} />

			<div className="d-flex gap-3 align-items-center">
				<input
					type="text"
					className="form-control"
					placeholder="Фильтровать по IMEI"
					value={imeiFilter}
					onChange={(e) => setImeiFilter(e.target.value)}
				/>
				<button className="btn btn-primary" onClick={() => setImeiFilter("")}>
					Очистить
				</button>
			</div>

			<table className="table table-striped table-hover table-bordered">
				<thead>
					<tr>
						<th>IMEI или системный ИД (Абонент)</th>
						<th>ИД Объекта</th>
						<th>Действия</th>
					</tr>
				</thead>
				<tbody>
					{visibleRows.map((row) => (
						<tr key={row.id}>
							<td>{row.abonent}</td>
							<td>{row.assetId}</td>
							<td
								style={{
									display: "flex",
									justifyContent: "center",
									alignItems: "center",
									gap: "0.5rem",
								}}
							>
								<button
									onClick={() => openCard(row)}
									className="btn btn-primary"
								>
									Редактировать
								</button>
								<button
									onClick={() => tryDelete(row)}
									className="btn btn-danger"
								>
									Удалить
								</button>
							</td>
						</tr>
					))}
				</tbody>
			</table>
		</div>
	);
}
