import { useState, type FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { settingsPutMutation } from "@/lib/queries";
import { buildSettingsPatch } from "@/lib/settingsDiff";
import type { Settings, SettingsEnvelope } from "@/lib/types";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { SECTIONS, sectionValues, type AnyFieldDef } from "./settingsSections";
import { styles as config } from "./styles";

const DARK = "@media (prefers-color-scheme: dark)";

/** The form is rendered once per page, so the message can hold a fixed id. */
const MISMATCH_ID = "web.password_mismatch";

const styles = stylex.create({
	form: {
		marginTop: "1rem",
		maxWidth: "48rem",
	},
	/** A `fieldset` has a browser default border and padding; the layout wants neither. */
	sections: {
		display: "flex",
		flexDirection: "column",
		gap: "1.5rem",
		borderStyle: "none",
		margin: 0,
		padding: 0,
	},
	section: {
		borderRadius: "0.25rem",
		borderWidth: 1,
		borderStyle: "solid",
		borderColor: colors.border,
		padding: "1rem",
	},
	legend: {
		paddingInline: "0.25rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		fontWeight: 600,
	},
	/** One column on a phone, two from `sm`. */
	fieldGrid: {
		display: "grid",
		gap: "0.75rem",
		gridTemplateColumns: {
			default: "repeat(1, minmax(0, 1fr))",
			"@media (min-width: 640px)": "repeat(2, minmax(0, 1fr))",
		},
	},
	label: {
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: {
			default: "oklch(37% 0.013 285.805)",
			[DARK]: "oklch(87.1% 0.006 286.286)",
		},
	},
	checkboxRow: {
		display: "flex",
		alignItems: "center",
		gap: "0.5rem",
	},
	field: {
		display: "flex",
		flexDirection: "column",
		gap: "0.25rem",
	},
	fieldInput: {
		borderRadius: "0.25rem",
		borderWidth: 1,
		borderStyle: "solid",
		borderColor: colors.borderStrong,
		backgroundColor: colors.surfaceRaised,
		color: colors.text,
		paddingInline: "0.5rem",
		paddingBlock: "0.25rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
	},
	derived: {
		color: colors.textMuted,
	},
	/** Both notices span the whole grid so the wrapped sentence stays readable. */
	spanRow: {
		gridColumn: { default: null, "@media (min-width: 640px)": "span 2 / span 2" },
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
	},
	passwordNotice: {
		color: { default: "oklch(55.5% 0.163 48.998)", [DARK]: "oklch(82.8% 0.189 84.429)" },
	},
	mismatchNotice: {
		color: colors.danger,
	},
	submitRow: {
		display: "flex",
		alignItems: "center",
		gap: "0.75rem",
	},
	save: {
		cursor: { default: "pointer", ":disabled": "not-allowed" },
		borderStyle: "none",
		borderRadius: "0.25rem",
		paddingInline: "1rem",
		paddingBlock: "0.375rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		fontWeight: 500,
		backgroundColor: {
			default: colors.primary,
			":disabled": "oklch(87.1% 0.006 286.286)",
			[DARK]: { default: colors.primary, ":disabled": "oklch(27.4% 0.006 286.033)" },
		},
		color: { default: colors.primaryText, ":disabled": "oklch(55.2% 0.016 285.938)" },
	},
});

function FieldLabel({ id, text, restart }: { id: string; text: string; restart: boolean }) {
	return (
		<label htmlFor={id} {...stylex.props(styles.label)}>
			{text}
			{restart && <span {...stylex.props(config.restartTag)}>needs restart</span>}
		</label>
	);
}

function FieldRow({
	section,
	def,
	value,
	restart,
	onChange,
}: {
	section: string;
	def: AnyFieldDef;
	value: unknown;
	restart: boolean;
	onChange: (value: unknown) => void;
}) {
	const id = `${section}.${def.key}`;
	if (def.kind === "boolean") {
		return (
			<div {...stylex.props(styles.checkboxRow)}>
				<input
					id={id}
					type="checkbox"
					checked={value as boolean}
					onChange={(e) => onChange(e.target.checked)}
					{...stylex.props(shared.focusRing)}
				/>
				<FieldLabel id={id} text={def.key} restart={restart} />
			</div>
		);
	}
	if (Array.isArray(def.kind)) {
		// `Select` renders its own `<label>` from a string, so the marker cannot be
		// placed inside that label the way `FieldLabel` does it; it goes through the
		// description slot instead, which puts it under the control and on the
		// trigger's `aria-describedby`. An enum key that owes a restart owes it just
		// as much as a number one, so it must be marked either way.
		return (
			<div {...stylex.props(styles.field)}>
				<Select
					variant="inline"
					label={def.key}
					value={value as string}
					onChange={onChange}
					options={def.kind.map((option) => ({ value: option, label: option }))}
					description={restart ? "needs restart" : undefined}
				/>
			</div>
		);
	}
	if (def.kind === "number") {
		const numeric = value as number;
		// An empty or unparseable number reads back as NaN. The form already refuses
		// to submit on it; this is what says so to a screen reader.
		return (
			<div {...stylex.props(styles.field)}>
				<FieldLabel id={id} text={def.key} restart={restart} />
				<input
					id={id}
					type="number"
					aria-invalid={Number.isNaN(numeric) || undefined}
					value={Number.isNaN(numeric) ? "" : numeric}
					onChange={(e) => onChange(e.target.valueAsNumber)}
					{...stylex.props(styles.fieldInput, shared.focusRing)}
				/>
			</div>
		);
	}
	return (
		<div {...stylex.props(styles.field)}>
			<FieldLabel id={id} text={def.key} restart={restart} />
			<input
				id={id}
				type="text"
				value={value as string}
				onChange={(e) => onChange(e.target.value)}
				{...stylex.props(styles.fieldInput, shared.focusRing)}
			/>
		</div>
	);
}

/**
 * The editable settings, in database mode only. Nothing here is ever disabled
 * for authority: under file authority the page renders definitions instead, so
 * this form is never drawn as a shell the reader cannot use.
 *
 * Which keys owe a restart is the server's answer, carried on the envelope's
 * `restart_required` list; whether one is owed *now* is `restart_pending` on
 * `/api/config/status`, which the shell notice reads.
 */
export default function SettingsForm({ envelope }: { envelope: SettingsEnvelope }) {
	const queryClient = useQueryClient();
	const mutation = useMutation(settingsPutMutation(queryClient));
	// Frozen at mount and re-frozen on save: diffing against live query data would
	// turn a background refetch's out-of-band changes into phantom user edits.
	const [baseline, setBaseline] = useState<Settings>(() => structuredClone(envelope.settings));
	const [edited, setEdited] = useState<Settings>(() => structuredClone(envelope.settings));
	const [password, setPassword] = useState("");
	const [confirm, setConfirm] = useState("");

	const restartKeys = new Set(envelope.restart_required);
	const passwordsMismatch = (password !== "" || confirm !== "") && password !== confirm;
	const hasInvalidNumber = SECTIONS.some(({ section, fields }) => {
		const values = sectionValues(edited, section);
		return (fields as readonly AnyFieldDef[]).some(
			(field) => field.kind === "number" && Number.isNaN(values[field.key]),
		);
	});
	const patch = buildSettingsPatch(baseline, edited, password === "" ? undefined : password);
	const saveDisabled = patch === null || passwordsMismatch || hasInvalidNumber || mutation.isPending;

	function setField(section: keyof Settings, key: string, value: unknown): void {
		setEdited((prev) => ({
			...prev,
			[section]: { ...sectionValues(prev, section), [key]: value },
		}));
	}

	function handleSubmit(event: FormEvent): void {
		event.preventDefault();
		if (patch === null || passwordsMismatch || hasInvalidNumber) return;
		mutation.mutate(patch, {
			onSuccess: (saved) => {
				setBaseline(structuredClone(saved.settings));
				setEdited(structuredClone(saved.settings));
				setPassword("");
				setConfirm("");
			},
		});
	}

	return (
		<form onSubmit={handleSubmit} {...stylex.props(styles.form)}>
			<fieldset disabled={mutation.isPending} {...stylex.props(styles.sections)}>
				{SECTIONS.map(({ section, title, fields }) => (
					<fieldset key={section} {...stylex.props(styles.section)}>
						<legend {...stylex.props(styles.legend)}>{title}</legend>
						<div {...stylex.props(styles.fieldGrid)}>
							{(fields as readonly AnyFieldDef[]).map((def) => (
								<FieldRow
									key={def.key}
									section={section}
									def={def}
									value={sectionValues(edited, section)[def.key]}
									restart={restartKeys.has(`${section}.${def.key}`)}
									onChange={(value) => setField(section, def.key, value)}
								/>
							))}
							{section === "web" && (
								<>
									<p {...stylex.props(styles.label)}>
										Authentication:{" "}
										{envelope.settings.web.auth_enabled ? "required" : "not configured"}{" "}
										<span {...stylex.props(styles.derived)}>
											(derived from whether a password is stored)
										</span>
									</p>
									<div {...stylex.props(styles.field)}>
										<label htmlFor="web.password" {...stylex.props(styles.label)}>
											password
										</label>
										<input
											id="web.password"
											type="password"
											autoComplete="new-password"
											aria-invalid={passwordsMismatch || undefined}
											aria-describedby={passwordsMismatch ? MISMATCH_ID : undefined}
											value={password}
											onChange={(e) => setPassword(e.target.value)}
											{...stylex.props(styles.fieldInput, shared.focusRing)}
										/>
									</div>
									<div {...stylex.props(styles.field)}>
										<label htmlFor="web.password_confirm" {...stylex.props(styles.label)}>
											confirm password
										</label>
										<input
											id="web.password_confirm"
											type="password"
											autoComplete="new-password"
											aria-invalid={passwordsMismatch || undefined}
											aria-describedby={passwordsMismatch ? MISMATCH_ID : undefined}
											value={confirm}
											onChange={(e) => setConfirm(e.target.value)}
											{...stylex.props(styles.fieldInput, shared.focusRing)}
										/>
									</div>
									{password !== "" && (
										<p {...stylex.props(styles.spanRow, styles.passwordNotice)}>
											Changing the password signs out every session; you will be asked to log in
											again.
										</p>
									)}
									{passwordsMismatch && (
										<p id={MISMATCH_ID} {...stylex.props(styles.spanRow, styles.mismatchNotice)}>
											Passwords do not match.
										</p>
									)}
								</>
							)}
						</div>
					</fieldset>
				))}
				<div {...stylex.props(styles.submitRow)}>
					<button type="submit" disabled={saveDisabled} {...stylex.props(styles.save, shared.focusRing)}>
						{mutation.isPending ? "Saving…" : "Save"}
					</button>
					{mutation.isError && <InlineError error={mutation.error} />}
				</div>
			</fieldset>
		</form>
	);
}
