import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { Link, useSearch } from "@tanstack/react-router";
import * as stylex from "@stylexjs/stylex";
import { clientDeleteMutation, clientPrefixesQuery, clientsQuery, groupsQuery } from "@/lib/queries";
import { formatTime } from "@/lib/format";
import type { Client, Group } from "@/lib/types";
import ClientEditDialog from "./ClientEditDialog";
import NetworkAssignments from "./NetworkAssignments";
import { ClientDisplayName } from "./clientIdentity";
import InlineError from "@/lib/InlineError";
import ConfigLockIndicator from "@/features/configuration/ConfigLockIndicator";
import { useAuthority, useReadOnlyConfig, type Authority } from "@/features/configuration/authority";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";

/**
 * Deleting an observed row discards runtime state the file never declared, so
 * it stays live under every authority; deleting a declared row contradicts the
 * file and is the one client DELETE the server answers 403 (ruling 7).
 *
 * The lock fails closed, so it also holds while authority is pending or
 * unreachable. There the file is a possibility and not a fact — `hand_edited`
 * alone cannot say which operator surface set the row — so the sentence names
 * the doubt rather than asserting a declaration, the way `provenanceOf` does.
 */
function declaredDeleteNote(authority: Authority): string {
	if (authority.state === "resolved") {
		return "This client is declared in the configuration file; remove it there and restart.";
	}
	return "nxdns cannot say whether this client is declared in the configuration file until it reports its configuration status, so deleting it stays locked.";
}

const styles = stylex.create({
	heading: {
		fontSize: "1.5rem",
		lineHeight: "2rem",
		fontWeight: 600,
	},
	empty: {
		marginTop: "1rem",
		color: colors.textMuted,
	},
	filterBar: {
		marginTop: "1rem",
		display: "flex",
		flexWrap: "wrap",
		alignItems: "center",
		gap: "0.75rem",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
	},
	table: {
		width: "100%",
		minWidth: "48rem",
		textAlign: "left",
		fontSize: "0.875rem",
		lineHeight: "1.25rem",
	},
	headRow: {
		borderBottomWidth: 1,
		borderBottomStyle: "solid",
		borderBottomColor: colors.border,
		color: colors.textMuted,
	},
	bodyRow: {
		borderBottomWidth: 1,
		borderBottomStyle: "solid",
		borderBottomColor: colors.border,
	},
	cell: {
		paddingInline: "0.75rem",
		paddingBlock: "0.5rem",
	},
	right: {
		textAlign: "right",
	},
	addressLink: {
		color: colors.primaryOnSurface,
		textDecorationLine: "none",
	},
	confirmGroup: {
		display: "inline-flex",
		flexWrap: "wrap",
		alignItems: "center",
		justifyContent: "flex-end",
		gap: "0.5rem",
	},
	actionGroup: {
		display: "inline-flex",
		alignItems: "center",
		gap: "0.5rem",
	},
	note: {
		fontSize: "0.75rem",
		lineHeight: "1rem",
		color: colors.textMuted,
	},
	dangerText: {
		color: colors.danger,
	},
	dimWhenDisabled: {
		opacity: { default: 1, ":disabled": 0.5 },
	},
});

export default function ClientsPage() {
	const { data: clients } = useSuspenseQuery(clientsQuery());
	const { data: prefixes } = useSuspenseQuery(clientPrefixesQuery());
	const { data: groups } = useSuspenseQuery(groupsQuery());
	const { group } = useSearch({ from: "/shell/clients" });
	const queryClient = useQueryClient();
	const deleteMutation = useMutation(clientDeleteMutation(queryClient));
	const [editing, setEditing] = useState<Client | null>(null);
	const [confirmingId, setConfirmingId] = useState<number | null>(null);
	const readOnly = useReadOnlyConfig();
	const authority = useAuthority();

	// A well-formed id the group list does not contain is a link to a group that
	// has since been deleted. It filters to nothing, which is the truth, and the
	// notice says so rather than quietly showing every client.
	const filterGroup: Group | undefined = group === undefined ? undefined : groups.find((row) => row.id === group);
	const rows = group === undefined ? clients : clients.filter((client) => client.group_id === group);

	return (
		<section>
			<h1 {...stylex.props(styles.heading)}>Clients</h1>
			{group !== undefined && (
				<div {...stylex.props(styles.filterBar)}>
					<span>
						{filterGroup !== undefined
							? `Showing clients in ${filterGroup.name}.`
							: `No group with id ${group} exists.`}
					</span>
					<Link to="/clients" search={{}} {...stylex.props(shared.linkButton, shared.focusRing)}>
						Clear filter
					</Link>
				</div>
			)}
			{clients.length === 0 ? (
				<p {...stylex.props(styles.empty)}>
					No clients yet. Rows appear automatically as devices on the network make DNS queries — there is
					nothing to create by hand.
				</p>
			) : rows.length === 0 ? (
				<p {...stylex.props(styles.empty)}>No clients match this filter.</p>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(styles.table)}>
						<thead>
							<tr {...stylex.props(styles.headRow)}>
								<th {...stylex.props(styles.cell)}>Address</th>
								<th {...stylex.props(styles.cell)}>Name</th>
								<th {...stylex.props(styles.cell)}>Group</th>
								<th {...stylex.props(styles.cell)}>First seen</th>
								<th {...stylex.props(styles.cell)}>Last seen</th>
								<th {...stylex.props(styles.cell)}>
									<span {...stylex.props(shared.srOnly)}>Actions</span>
								</th>
							</tr>
						</thead>
						<tbody>
							{rows.map((client) => (
								<tr key={client.id} {...stylex.props(styles.bodyRow)}>
									<td {...stylex.props(styles.cell, shared.mono)}>
										<Link
											to="/clients/$id"
											params={{ id: String(client.id) }}
											{...stylex.props(styles.addressLink, shared.focusRing)}
										>
											{client.ip}
										</Link>
									</td>
									<td {...stylex.props(styles.cell)}>
										<ClientDisplayName client={client} />
									</td>
									<td {...stylex.props(styles.cell)}>{client.group}</td>
									<td {...stylex.props(styles.cell)}>{formatTime(client.first_seen)}</td>
									<td {...stylex.props(styles.cell)}>{formatTime(client.last_seen)}</td>
									<td {...stylex.props(styles.cell, styles.right)}>
										{confirmingId === client.id ? (
											<span {...stylex.props(styles.confirmGroup)}>
												{/* Authority is polled, so it can turn while a confirmation
												    sits open. The confirm path reads it on every render
												    rather than trusting the state that opened it. */}
												<span {...stylex.props(styles.note)}>
													{readOnly && client.hand_edited
														? declaredDeleteNote(authority)
														: "Deleted clients re-materialize on their next DNS query."}
												</span>
												{readOnly && client.hand_edited ? (
													<ConfigLockIndicator />
												) : (
													<button
														type="button"
														onClick={() => {
															setConfirmingId(null);
															deleteMutation.mutate(client.id);
														}}
														{...stylex.props(
															shared.smallButton,
															styles.dangerText,
															shared.focusRing,
														)}
													>
														Confirm delete
													</button>
												)}
												<button
													type="button"
													onClick={() => setConfirmingId(null)}
													{...stylex.props(shared.smallButton, shared.focusRing)}
												>
													Cancel
												</button>
											</span>
										) : (
											<span {...stylex.props(styles.actionGroup)}>
												{/* Naming a client writes configuration, so the affordance is
												    absent — not disabled — wherever the write cannot land. */}
												{readOnly ? (
													<ConfigLockIndicator />
												) : (
													<button
														type="button"
														onClick={() => setEditing(client)}
														{...stylex.props(shared.smallButton, shared.focusRing)}
													>
														Edit
													</button>
												)}
												<button
													type="button"
													onClick={() => setConfirmingId(client.id)}
													disabled={readOnly && client.hand_edited}
													title={
														readOnly && client.hand_edited
															? declaredDeleteNote(authority)
															: undefined
													}
													{...stylex.props(
														shared.smallButton,
														styles.dangerText,
														styles.dimWhenDisabled,
														shared.focusRing,
													)}
												>
													Delete
												</button>
											</span>
										)}
									</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			)}
			<InlineError error={deleteMutation.error} />
			{editing !== null && <ClientEditDialog client={editing} groups={groups} onClose={() => setEditing(null)} />}
			<NetworkAssignments prefixes={prefixes} groups={groups} />
		</section>
	);
}
