import { useReducer, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import { clientPrefixesPutMutation } from "@/lib/queries";
import type { ClientPrefix, Group } from "@/lib/types";
import { defaultGroupId } from "@/lib/defaultGroup";
import {
	firstProblem,
	initPrefixEditor,
	isDirty,
	prefixEditorReducer,
	toInputs,
	type PrefixEditorAction,
	type PrefixProblem,
} from "./prefixEditor";
import InlineError from "@/lib/InlineError";
import AuthorityGate from "@/features/configuration/AuthorityGate";
import Select from "@/ui/Select";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";

interface Props {
	prefixes: ClientPrefix[];
	groups: Group[];
}

/** The editor is rendered once per page, so the message can hold a fixed id. */
const VALIDATION_ID = "network-assignments-validation";

const styles = stylex.create({
	section: {
		marginTop: "2.5rem",
	},
	heading: {
		fontSize: "1.25rem",
		lineHeight: "1.75rem",
		fontWeight: 600,
	},
	headingKey: {
		marginLeft: "0.5rem",
		fontSize: "0.75rem",
		lineHeight: "1rem",
		fontWeight: 400,
		color: colors.textMuted,
	},
	intro: {
		marginTop: "0.25rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.textMuted,
	},
	empty: {
		marginTop: "1rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.textMuted,
	},
	rows: {
		display: "flex",
		flexDirection: "column",
		gap: "0.5rem",
		marginTop: "1rem",
		listStyleType: "none",
		padding: 0,
	},
	row: {
		display: "flex",
		flexWrap: "wrap",
		alignItems: "center",
		gap: "0.5rem",
	},
	prefixInput: {
		width: "13rem",
	},
	priorityInput: {
		width: "5rem",
	},
	removeButton: {
		cursor: { default: "pointer", ":disabled": "not-allowed" },
		borderRadius: "0.25rem",
		borderWidth: 1,
		borderStyle: "solid",
		borderColor: colors.borderStrong,
		backgroundColor: "transparent",
		paddingInline: "0.5rem",
		paddingBlock: "0.375rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.danger,
	},
	validation: {
		marginTop: "0.5rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
		color: colors.danger,
	},
	actions: {
		display: "flex",
		gap: "0.5rem",
		marginTop: "1rem",
	},
	table: {
		width: "100%",
		minWidth: "max-content",
		borderCollapse: "collapse",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
	},
});

/**
 * Address ranges that assign a group to every device inside them.
 *
 * The section is a configuration rendering, so it goes through the authority
 * gate: the editor exists only where a save can land, and file authority gets
 * the assignments as a table rather than a form nobody may submit.
 */
export default function NetworkAssignments({ prefixes, groups }: Props) {
	return (
		<section {...stylex.props(styles.section)}>
			<h2 {...stylex.props(styles.heading)}>
				Network assignments
				<code {...stylex.props(shared.mono, styles.headingKey)}>client_prefixes</code>
			</h2>
			<p {...stylex.props(styles.intro)}>
				An address range assigns its group to every device inside it, for devices with no row of their own. The
				highest priority match wins.
			</p>
			<AuthorityGate>
				{(status) =>
					status.authority === "database" ? (
						<AssignmentsEditor prefixes={prefixes} groups={groups} />
					) : (
						<AssignmentsTable prefixes={prefixes} />
					)
				}
			</AuthorityGate>
		</section>
	);
}

function AssignmentsTable({ prefixes }: { prefixes: ClientPrefix[] }) {
	if (prefixes.length === 0) return <p {...stylex.props(styles.empty)}>The file declares no network assignments.</p>;
	return (
		<div {...stylex.props(shared.tableWrap)}>
			<table {...stylex.props(styles.table)}>
				<thead>
					<tr>
						<th {...stylex.props(shared.th)}>Range</th>
						<th {...stylex.props(shared.th)}>Group</th>
						<th {...stylex.props(shared.th)}>Priority</th>
					</tr>
				</thead>
				<tbody>
					{prefixes.map((prefix) => (
						<tr key={prefix.id}>
							<td {...stylex.props(shared.td, shared.mono)}>{prefix.prefix}</td>
							<td {...stylex.props(shared.td)}>{prefix.group}</td>
							<td {...stylex.props(shared.td, shared.tabularNums)}>{prefix.priority}</td>
						</tr>
					))}
				</tbody>
			</table>
		</div>
	);
}

/**
 * The list is saved as a whole, so the editor holds every row and the PUT
 * replaces the set. Reached only under resolved database authority: the gate
 * above owns that decision, and no control here consults it a second time.
 */
function AssignmentsEditor({ prefixes, groups }: Props) {
	const queryClient = useQueryClient();
	const mutation = useMutation(clientPrefixesPutMutation(queryClient));
	const [state, apply] = useReducer(prefixEditorReducer, prefixes, initPrefixEditor);
	const [validation, setValidation] = useState<PrefixProblem | null>(null);
	const dirty = isDirty(state);
	const fallbackGroupId = defaultGroupId(groups);
	const groupOptions = groups.map((group) => ({ value: String(group.id), label: group.name }));

	// A problem names a row by position, and every action here can move, add or
	// delete a position. The message describes the rows Save read, so it dies
	// with them rather than drifting onto whatever row inherits the index.
	const dispatch = (action: PrefixEditorAction) => {
		setValidation(null);
		apply(action);
	};

	/** True for the one input the current message is about; nothing else is marked. */
	const invalid = (index: number, field: PrefixProblem["field"]): true | undefined =>
		validation !== null && validation.index === index && validation.field === field ? true : undefined;

	const save = () => {
		const problem = firstProblem(state.rows);
		setValidation(problem);
		if (problem !== null) return;
		mutation.mutate(toInputs(state.rows), {
			onSuccess: (stored) => dispatch({ type: "reset", prefixes: stored }),
		});
	};

	return (
		<>
			{state.rows.length === 0 ? (
				<p {...stylex.props(styles.empty)}>No network assignments configured.</p>
			) : (
				<ul {...stylex.props(styles.rows)}>
					{state.rows.map((row, index) => (
						<li key={index} {...stylex.props(styles.row)}>
							<input
								type="text"
								aria-label={`Range ${index + 1}`}
								aria-invalid={invalid(index, "prefix")}
								aria-describedby={invalid(index, "prefix") && VALIDATION_ID}
								placeholder="192.168.1.0/24"
								value={row.prefix}
								onChange={(event) =>
									dispatch({ type: "edit", index, patch: { prefix: event.target.value } })
								}
								{...stylex.props(shared.smallInput, styles.prefixInput, shared.focusRing)}
							/>
							<Select
								aria-label={`Group for range ${index + 1}`}
								variant="inline"
								value={String(row.group_id)}
								onChange={(value) =>
									dispatch({ type: "edit", index, patch: { group_id: Number(value) } })
								}
								options={groupOptions}
							/>
							<input
								type="text"
								inputMode="numeric"
								aria-label={`Priority for range ${index + 1}`}
								aria-invalid={invalid(index, "priority")}
								aria-describedby={invalid(index, "priority") && VALIDATION_ID}
								placeholder="100"
								value={row.priority}
								onChange={(event) =>
									dispatch({ type: "edit", index, patch: { priority: event.target.value } })
								}
								{...stylex.props(shared.smallInput, styles.priorityInput, shared.focusRing)}
							/>
							<button
								type="button"
								onClick={() => dispatch({ type: "remove", index })}
								{...stylex.props(styles.removeButton, shared.focusRing)}
							>
								Remove
							</button>
						</li>
					))}
				</ul>
			)}
			{validation !== null && (
				<p id={VALIDATION_ID} role="alert" {...stylex.props(styles.validation)}>
					{validation.message}
				</p>
			)}
			<InlineError error={mutation.error} />
			<div {...stylex.props(styles.actions)}>
				<button
					type="button"
					onClick={() => dispatch({ type: "add", groupId: fallbackGroupId })}
					{...stylex.props(shared.button, shared.focusRing)}
				>
					Add range
				</button>
				<button
					type="button"
					onClick={save}
					disabled={!dirty || mutation.isPending}
					{...stylex.props(shared.primaryButton, shared.focusRing)}
				>
					Save assignments
				</button>
				{dirty && (
					<button
						type="button"
						onClick={() => dispatch({ type: "reset", prefixes })}
						{...stylex.props(shared.button, shared.focusRing)}
					>
						Discard changes
					</button>
				)}
			</div>
		</>
	);
}
