"use client";

import React from "react";

import {
	extractBranchNumberInputFromBranchId,
	formatBranchIdFromNumberInput,
	normalizeBranchIdInput,
} from "@/lib/frontend/admin/users/userManagementUx";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export default function BranchNumberInput({
	id,
	branchId,
	onBranchIdChange,
	disabled,
	invalid = false,
	describedBy,
}) {
	const [numberDraft, setNumberDraft] = React.useState(() =>
		extractBranchNumberInputFromBranchId(branchId),
	);

	React.useEffect(() => {
		const normalizedExternalBranchId = normalizeBranchIdInput(branchId);
		const currentDerivedBranchId = formatBranchIdFromNumberInput(numberDraft);

		// Keep user typing stable (e.g. "01" stays visible) while syncing true external changes
		// like dialog open/reset/user switch.
		if (currentDerivedBranchId === normalizedExternalBranchId) return;

		setNumberDraft(extractBranchNumberInputFromBranchId(branchId));
	}, [branchId, numberDraft]);

	const wrapperClass = invalid
		? "border-destructive"
		: "border-input";

	return (
		<div className="grid gap-2">
			<Label htmlFor={id}>Niederlassung</Label>

			<div
				className={`flex h-9 items-stretch overflow-hidden rounded-md border ${wrapperClass}`}
			>
				<span className="inline-flex shrink-0 items-center border-r bg-muted px-3 text-sm text-muted-foreground">
					NL
				</span>

				<Input
					id={id}
					type="text"
					inputMode="numeric"
					pattern="[0-9]*"
					value={numberDraft}
					onChange={(e) => {
						const nextNumberDraft = String(e.target.value || "").replace(
							/\D+/g,
							"",
						);
						setNumberDraft(nextNumberDraft);
						onBranchIdChange?.(formatBranchIdFromNumberInput(nextNumberDraft));
					}}
					disabled={disabled}
					placeholder="z. B. 01"
					className="h-full rounded-none border-0 shadow-none focus-visible:ring-0"
					aria-invalid={invalid ? "true" : "false"}
					aria-describedby={describedBy}
				/>
			</div>
		</div>
	);
}
