import { useQuery } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import { settingsQuery } from "@/lib/queries";
import AuthorityGate from "./AuthorityGate";
import FileModeNote from "./FileModeNote";
import QueryPanel from "./QueryPanel";
import ReloadCertsAction from "./ReloadCertsAction";
import SettingsDefinitions from "./SettingsDefinitions";
import SettingsForm from "./SettingsForm";
import { styles } from "./styles";

/**
 * System: what this process is running with. No tabs — the settings registry
 * is already sectioned, and splitting it further would hide the section the
 * reader came for behind a guess about which tab holds it.
 *
 * "Reload certificates" sits above the gate: it is a runtime action on the
 * running listeners, so it works whatever owns the configuration and whether
 * or not `/api/config/status` has answered.
 */
export default function SystemPage() {
	const settings = useQuery(settingsQuery());

	return (
		<section>
			<h1 {...stylex.props(styles.heading)}>System</h1>
			<p {...stylex.props(styles.intro)}>
				The service, storage, logging, TLS and web settings this nxdns process is running with.
			</p>
			<ReloadCertsAction />
			<AuthorityGate>
				{(status) =>
					status.authority === "managed_file" ? (
						<>
							<FileModeNote path={status.path} />
							<QueryPanel query={settings}>
								{(envelope) => <SettingsDefinitions settings={envelope.settings} />}
							</QueryPanel>
						</>
					) : (
						<QueryPanel query={settings}>{(envelope) => <SettingsForm envelope={envelope} />}</QueryPanel>
					)
				}
			</AuthorityGate>
		</section>
	);
}
