import { useState } from "react";
import { useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import { clientDeleteMutation, clientPrefixesQuery, clientsQuery, groupsQuery } from "@/lib/queries";
import { formatTime } from "@/lib/format";
import type { Client } from "@/lib/types";
import ClientEditDialog from "./ClientEditDialog";
import PrefixesEditor from "./PrefixesEditor";
import InlineError from "@/lib/InlineError";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { READ_ONLY_HINT, useReadOnlyConfig } from "@/features/settings/authority";

/**
 * Deleting an observed row discards runtime state the file never declared, so
 * it stays live under file authority; deleting a hand-edited row contradicts
 * the file and is the one client DELETE the server answers 403 (ruling 7).
 */
const DECLARED_CLIENT_NOTE = "This client is declared in the configuration file; remove it there and restart.";

const styles = stylex.create({
	heading: {
		fontSize: "1.5rem",
		lineHeight: "2rem",
		fontWeight: 600,
	},
	empty: {
		marginTop: "1rem",
		color: colors.textMuted,
	},
	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",
	},
	mono: {
		fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
	},
	right: {
		textAlign: "right",
	},
	dash: {
		color: colors.textMuted,
	},
	badge: {
		marginLeft: "0.5rem",
		borderRadius: "0.25rem",
		backgroundColor: colors.primary,
		paddingInline: "0.375rem",
		paddingBlock: "0.125rem",
		fontSize: "0.75rem",
		lineHeight: "1rem",
		fontWeight: 500,
		color: colors.primaryText,
	},
	confirmGroup: {
		display: "inline-flex",
		flexWrap: "wrap",
		alignItems: "center",
		justifyContent: "flex-end",
		gap: "0.5rem",
	},
	actionGroup: {
		display: "inline-flex",
		gap: "0.5rem",
	},
	note: {
		fontSize: "0.75rem",
		lineHeight: "1rem",
		color: colors.textMuted,
	},
	dangerText: {
		color: colors.danger,
	},
	dimWhenDisabled: {
		opacity: { default: 1, ":disabled": 0.5 },
	},
	/**
	 * The accessible name of the actions column, kept out of the visual table
	 * without leaving the accessibility tree.
	 */
	srOnly: {
		position: "absolute",
		width: 1,
		height: 1,
		padding: 0,
		margin: -1,
		overflow: "hidden",
		clipPath: "inset(50%)",
		whiteSpace: "nowrap",
		borderWidth: 0,
	},
});

export default function ClientsPage() {
	const { data: clients } = useSuspenseQuery(clientsQuery());
	const { data: prefixes } = useSuspenseQuery(clientPrefixesQuery());
	const { data: groups } = useSuspenseQuery(groupsQuery());
	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();

	return (
		<section>
			<h1 {...stylex.props(styles.heading)}>Clients</h1>
			{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>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(styles.table)}>
						<thead>
							<tr {...stylex.props(styles.headRow)}>
								<th {...stylex.props(styles.cell)}>IP</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(styles.srOnly)}>Actions</span>
								</th>
							</tr>
						</thead>
						<tbody>
							{clients.map((client) => (
								<tr key={client.id} {...stylex.props(styles.bodyRow)}>
									<td {...stylex.props(styles.cell, styles.mono)}>{client.ip}</td>
									<td {...stylex.props(styles.cell)}>
										{client.name === "" ? (
											<span {...stylex.props(styles.dash)}>—</span>
										) : (
											client.name
										)}
										{client.hand_edited && <span {...stylex.props(styles.badge)}>edited</span>}
									</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)}>
												<span {...stylex.props(styles.note)}>
													Deleted clients re-materialize on their next DNS query.
												</span>
												<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)}>
												<button
													type="button"
													onClick={() => setEditing(client)}
													disabled={readOnly}
													title={readOnly ? READ_ONLY_HINT : undefined}
													{...stylex.props(
														shared.smallButton,
														styles.dimWhenDisabled,
														shared.focusRing,
													)}
												>
													Edit
												</button>
												<button
													type="button"
													onClick={() => setConfirmingId(client.id)}
													disabled={readOnly && client.hand_edited}
													title={
														readOnly && client.hand_edited
															? DECLARED_CLIENT_NOTE
															: 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)} />}
			<PrefixesEditor prefixes={prefixes} groups={groups} />
		</section>
	);
}
