"use client"; import { useState } from "react"; import type { KeyboardEvent } from "react"; import { Loader2, UserPlus } from "lucide-react"; import { lookupUserByEmail, type UserLookupResult, } from "@/app/lib/mikeApi"; import { PillButton } from "@/app/components/ui/pill-button"; import { cn } from "@/app/lib/utils"; const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; interface AddUserInputProps { onAdd: (user: UserLookupResult) => Promise | void; validateEmail?: (email: string) => Promise | string | null; busy?: boolean; placeholder?: string; autoFocus?: boolean; submitLabel?: string; className?: string; } export function AddUserInput({ onAdd, validateEmail, busy = false, placeholder = "Add by email...", autoFocus = false, submitLabel = "Add user", className, }: AddUserInputProps) { const [input, setInput] = useState(""); const [checking, setChecking] = useState(false); const [error, setError] = useState(null); const trimmedEmail = input.trim().toLowerCase(); const showAddButton = trimmedEmail.length > 0; async function commitUser() { const email = trimmedEmail; if (!email || busy || checking) return; if (!EMAIL_RE.test(email)) { setError("Enter a valid email."); return; } setError(null); setChecking(true); try { const validationError = await validateEmail?.(email); if (validationError) { setError(validationError); return; } const user = await lookupUserByEmail(email); if (!user.exists) { setError(`${email} does not belong to a Mike user.`); return; } await onAdd(user); setInput(""); } catch (err) { setError( err instanceof Error ? err.message : "Could not add this user. Try again.", ); } finally { setChecking(false); } } function handleKeyDown(event: KeyboardEvent) { if (event.key === "Enter" || event.key === ",") { event.preventDefault(); void commitUser(); } } return (
{ setInput(event.target.value); setError(null); }} onKeyDown={handleKeyDown} placeholder={placeholder} className="min-w-0 flex-1 bg-transparent text-sm text-gray-700 outline-none placeholder:text-gray-400" autoFocus={autoFocus} /> {showAddButton && ( event.preventDefault()} onClick={() => void commitUser()} disabled={busy || checking} title={submitLabel} className="h-6 shrink-0 px-2.5 text-[11px] leading-none" > {(busy || checking) && ( )} Add )}
{error &&

{error}

}
); }