import { useId, useState, type FormEvent } from "react";
import { useSuspenseQuery } from "@tanstack/react-query";
import {
	forwardZoneCreateMutation,
	forwardZoneDeleteMutation,
	forwardZoneUpdateMutation,
	forwardZonesQuery,
} from "@/lib/queries";
import type { ForwardZone, ForwardZoneInput } from "@/lib/types";
import InlineError from "@/lib/InlineError";
import { useCrudForm } from "@/ui/useCrudForm";
import {
	formCardClass,
	inputClass,
	largeButtonClass,
	largePrimaryButtonClass,
	rowButtonClass,
	tableWrapClass,
} from "@/ui/classes";

function ZoneForm({
	initial,
	busy,
	error,
	onSubmit,
	onCancel,
}: {
	initial?: ForwardZone;
	busy: boolean;
	error: unknown;
	onSubmit: (input: ForwardZoneInput) => void;
	onCancel: () => void;
}) {
	const id = useId();
	const [zone, setZone] = useState(initial?.zone ?? "");
	const [resolver, setResolver] = useState(initial?.resolver ?? "");

	function submit(event: FormEvent<HTMLFormElement>) {
		event.preventDefault();
		onSubmit({ zone: zone.trim(), resolver: resolver.trim() });
	}

	return (
		<form onSubmit={submit} className={formCardClass}>
			<h3 className="font-medium">{initial === undefined ? "New forward zone" : `Edit ${initial.zone}`}</h3>
			<div>
				<label htmlFor={`${id}-zone`} className="block text-sm font-medium">
					Zone
				</label>
				<input
					id={`${id}-zone`}
					required
					value={zone}
					onChange={(event) => setZone(event.target.value)}
					placeholder="lan.home"
					className={inputClass}
				/>
			</div>
			<div>
				<label htmlFor={`${id}-resolver`} className="block text-sm font-medium">
					Resolver
				</label>
				<input
					id={`${id}-resolver`}
					required
					value={resolver}
					onChange={(event) => setResolver(event.target.value)}
					placeholder="udp://192.168.1.1:53"
					className={inputClass}
				/>
			</div>
			<div className="flex gap-2">
				<button type="submit" disabled={busy} className={largePrimaryButtonClass}>
					{busy ? "Saving…" : "Save"}
				</button>
				<button type="button" onClick={onCancel} className={largeButtonClass}>
					Cancel
				</button>
			</div>
			<InlineError error={error} />
		</form>
	);
}

export default function ZonesTab() {
	const zones = useSuspenseQuery(forwardZonesQuery()).data;
	const { create, update, remove, form, openForm, closeForm, onSubmit, onDelete } = useCrudForm<
		ForwardZone,
		ForwardZoneInput
	>({
		create: forwardZoneCreateMutation,
		update: forwardZoneUpdateMutation,
		remove: forwardZoneDeleteMutation,
		confirmDelete: (zone) => `Delete forward zone "${zone.zone}"?`,
	});

	return (
		<div>
			<div className="mt-4 flex items-center justify-between">
				<p className="text-sm text-zinc-500">
					Names under these zones go to their own resolver. Changes apply live.
				</p>
				<button type="button" onClick={() => openForm({ mode: "create" })} className={largePrimaryButtonClass}>
					Add zone
				</button>
			</div>
			<InlineError error={remove.error} />
			{form?.mode === "create" && (
				<ZoneForm busy={create.isPending} error={create.error} onSubmit={onSubmit} onCancel={closeForm} />
			)}
			<div className={tableWrapClass}>
				<table className="w-full text-left text-sm">
					<thead>
						<tr className="border-b border-zinc-200 text-zinc-500 dark:border-zinc-800">
							<th scope="col" className="py-2 pr-4 font-medium">
								Zone
							</th>
							<th scope="col" className="py-2 pr-4 font-medium">
								Resolver
							</th>
							<th scope="col" className="py-2">
								<span className="sr-only">Actions</span>
							</th>
						</tr>
					</thead>
					<tbody>
						{zones.length === 0 && (
							<tr>
								<td colSpan={3} className="py-4 text-zinc-500">
									No forward zones yet.
								</td>
							</tr>
						)}
						{zones.map((zone) => (
							<tr key={zone.id} className="border-b border-zinc-100 dark:border-zinc-900">
								{form?.mode === "edit" && form.entity.id === zone.id ? (
									<td colSpan={3}>
										<ZoneForm
											initial={zone}
											busy={update.isPending}
											error={update.error}
											onSubmit={onSubmit}
											onCancel={closeForm}
										/>
									</td>
								) : (
									<>
										<td className="py-2 pr-4 font-mono">{zone.zone}</td>
										<td className="py-2 pr-4 font-mono">{zone.resolver}</td>
										<td className="py-2 text-right whitespace-nowrap">
											<button
												type="button"
												onClick={() => openForm({ mode: "edit", entity: zone })}
												className={rowButtonClass}
											>
												Edit
											</button>
											<button
												type="button"
												onClick={() => onDelete(zone)}
												disabled={remove.isPending}
												className={`${rowButtonClass} text-red-600 dark:text-red-400`}
											>
												Delete
											</button>
										</td>
									</>
								)}
							</tr>
						))}
					</tbody>
				</table>
			</div>
		</div>
	);
}
