import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as stylex from "@stylexjs/stylex";
import InlineError from "@/lib/InlineError";
import { upstreamCreateMutation, upstreamDeleteMutation, upstreamUpdateMutation, upstreamsQuery } from "@/lib/queries";
import type { Upstream, UpstreamInput } from "@/lib/types";
import ConfirmDialog from "@/ui/ConfirmDialog";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import Switch from "@/ui/Switch";
import AuthorityGate from "./AuthorityGate";
import FileModeNote from "./FileModeNote";
import QueryPanel from "./QueryPanel";
import UpstreamForm from "./UpstreamForm";
import { styles as config } from "./styles";

const INTRO = "The pool is rebuilt as you save, so an edit here applies to the next query.";

const styles = stylex.create({
	url: {
		display: "block",
		maxWidth: "18rem",
		overflow: "hidden",
		textOverflow: "ellipsis",
		whiteSpace: "nowrap",
		fontWeight: 500,
	},
	actions: {
		display: "flex",
		gap: "0.75rem",
	},
	dimWhenDisabled: {
		opacity: { default: 1, ":disabled": 0.5 },
	},
	absent: {
		color: colors.textMuted,
	},
});

export default function UpstreamsTab() {
	const upstreams = useQuery(upstreamsQuery());
	return (
		<AuthorityGate>
			{(status) => (
				<div>
					<p {...stylex.props(config.intro)}>{INTRO}</p>
					{status.authority === "managed_file" && <FileModeNote path={status.path} />}
					<QueryPanel query={upstreams}>
						{(rows) =>
							status.authority === "managed_file" ? (
								<UpstreamsReadOnly upstreams={rows} />
							) : (
								<UpstreamsEditor upstreams={rows} />
							)
						}
					</QueryPanel>
				</div>
			)}
		</AuthorityGate>
	);
}

function UpstreamsReadOnly({ upstreams }: { upstreams: Upstream[] }) {
	return (
		<section {...stylex.props(config.panel)}>
			<h2 {...stylex.props(config.panelHeading)}>
				Upstream pool
				<code {...stylex.props(shared.mono, config.panelKey)}>upstreams</code>
			</h2>
			{upstreams.length === 0 ? (
				<p {...stylex.props(config.empty)}>The file declares no upstreams.</p>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(config.table)}>
						<thead>
							<tr>
								<th {...stylex.props(shared.th)}>URL</th>
								<th {...stylex.props(shared.th)}>Priority</th>
								<th {...stylex.props(shared.th)}>Enabled</th>
								<th {...stylex.props(shared.th)}>TLS name</th>
							</tr>
						</thead>
						<tbody>
							{upstreams.map((u) => (
								<tr key={u.id}>
									<td {...stylex.props(shared.td, shared.mono)}>{u.url}</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{u.priority}</td>
									<td {...stylex.props(shared.td)}>{String(u.enabled)}</td>
									<td {...stylex.props(shared.td)}>
										{u.tls_name === "" ? (
											<span {...stylex.props(styles.absent)}>empty</span>
										) : (
											u.tls_name
										)}
									</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			)}
		</section>
	);
}

function UpstreamsEditor({ upstreams }: { upstreams: Upstream[] }) {
	const queryClient = useQueryClient();
	const [editing, setEditing] = useState<Upstream | null>(null);
	const [pendingDelete, setPendingDelete] = useState<Upstream | null>(null);

	const create = useMutation(upstreamCreateMutation(queryClient));
	const save = useMutation(upstreamUpdateMutation(queryClient));
	const toggle = useMutation(upstreamUpdateMutation(queryClient));
	const remove = useMutation(upstreamDeleteMutation(queryClient));

	async function submitForm(input: UpstreamInput) {
		if (editing === null) {
			await create.mutateAsync(input);
		} else {
			await save.mutateAsync({ id: editing.id, input });
			setEditing(null);
		}
	}

	function toggleEnabled(u: Upstream) {
		toggle.mutate({
			id: u.id,
			input: { url: u.url, priority: u.priority, enabled: !u.enabled, tls_name: u.tls_name },
		});
	}

	function confirmDelete() {
		if (pendingDelete === null) return;
		remove.mutate(pendingDelete.id);
		setPendingDelete(null);
	}

	const formError = editing === null ? create.error : save.error;
	const tableError = remove.error ?? toggle.error;

	return (
		<div>
			{upstreams.length === 0 ? (
				<p {...stylex.props(config.empty)}>No upstreams yet. Add one below.</p>
			) : (
				<div {...stylex.props(shared.tableWrap)}>
					<table {...stylex.props(config.table)}>
						<thead>
							<tr>
								<th {...stylex.props(shared.th)}>URL</th>
								<th {...stylex.props(shared.th)}>Priority</th>
								<th {...stylex.props(shared.th)}>Enabled</th>
								<th {...stylex.props(shared.th)}>TLS name</th>
								<th {...stylex.props(shared.th)}>
									<span {...stylex.props(shared.srOnly)}>Actions</span>
								</th>
							</tr>
						</thead>
						<tbody>
							{upstreams.map((u) => (
								<tr key={u.id}>
									<td {...stylex.props(shared.td)}>
										<span {...stylex.props(styles.url)} title={u.url}>
											{u.url}
										</span>
									</td>
									<td {...stylex.props(shared.td, shared.tabularNums)}>{u.priority}</td>
									<td {...stylex.props(shared.td)}>
										<Switch
											aria-label={`${u.url} enabled`}
											isSelected={u.enabled}
											isDisabled={toggle.isPending}
											onChange={() => toggleEnabled(u)}
										/>
									</td>
									<td {...stylex.props(shared.td)}>{u.tls_name === "" ? "—" : u.tls_name}</td>
									<td {...stylex.props(shared.td)}>
										<div {...stylex.props(styles.actions)}>
											<button
												type="button"
												onClick={() => setEditing(u)}
												{...stylex.props(shared.linkButton, shared.focusRing)}
											>
												Edit
											</button>
											<button
												type="button"
												onClick={() => setPendingDelete(u)}
												disabled={remove.isPending}
												{...stylex.props(
													shared.dangerLinkButton,
													styles.dimWhenDisabled,
													shared.focusRing,
												)}
											>
												Delete
											</button>
										</div>
									</td>
								</tr>
							))}
						</tbody>
					</table>
				</div>
			)}
			<InlineError error={tableError} />

			<UpstreamForm
				key={editing?.id ?? "add"}
				initial={editing ?? undefined}
				busy={editing === null ? create.isPending : save.isPending}
				error={formError}
				onSubmit={submitForm}
				onCancel={editing === null ? undefined : () => setEditing(null)}
			/>

			<ConfirmDialog
				isOpen={pendingDelete !== null}
				title="Delete upstream"
				message={
					pendingDelete === null
						? ""
						: `Delete upstream "${pendingDelete.url}"? Queries stop being forwarded to it.`
				}
				confirmLabel="Delete"
				onConfirm={confirmDelete}
				onCancel={() => setPendingDelete(null)}
			/>
		</div>
	);
}
