import { createDeviceRow } from "../../../model/adapters.js";
import { getDeviceDetail } from "../../../api/devices.js";
import { useEffect, useRef, useState } from "react";
//#region src/plus/saasDevice/devicePlanning/modules/deviceDetail/hooks/useDeviceDetail.ts
/** 管理详情抽屉的当前 tab、设备详情补拉取和 integrated 设备 tab 保护。 */
const useDeviceDetail = ({ open, record, initialTab, translation }) => {
	const [activeTab, setActiveTab] = useState("info");
	const [detailRecord, setDetailRecord] = useState();
	const detailFetchedIdRef = useRef();
	const displayRecord = detailRecord || record;
	const activeKind = (displayRecord === null || displayRecord === void 0 ? void 0 : displayRecord._raw.type_kind) || "smart";
	const isComposite = (displayRecord === null || displayRecord === void 0 ? void 0 : displayRecord._raw.structure) === "composite";
	useEffect(() => {
		if (open) {
			setActiveTab(initialTab);
			setDetailRecord(record);
			detailFetchedIdRef.current = void 0;
		}
	}, [
		initialTab,
		open,
		record === null || record === void 0 ? void 0 : record.id
	]);
	useEffect(() => {
		if (!open || !(record === null || record === void 0 ? void 0 : record.id)) return;
		if (!(activeTab === "info" || detailFetchedIdRef.current !== record.id)) return;
		detailFetchedIdRef.current = record.id;
		getDeviceDetail(record.id).then((detail) => {
			if (detail) setDetailRecord(createDeviceRow(detail, translation));
		}).catch(() => {
			setDetailRecord(record);
		});
	}, [
		activeTab,
		open,
		record,
		record === null || record === void 0 ? void 0 : record.id,
		translation
	]);
	useEffect(() => {
		if (activeKind === "integrated" && activeTab !== "info") setActiveTab("info");
		if (activeTab === "buildIns" && !isComposite) setActiveTab("info");
	}, [
		activeKind,
		activeTab,
		isComposite
	]);
	return {
		activeTab,
		activeKind,
		displayRecord,
		setActiveTab
	};
};
//#endregion
export { useDeviceDetail };
