"use client";

import React from "react";
import { Pencil } from "lucide-react";

import {
	Dialog,
	DialogContent,
	DialogDescription,
	DialogHeader,
	DialogTitle,
	DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";

import EditUserForm from "@/components/admin/users/edit-user/EditUserForm";
import { useEditUserDialog } from "@/components/admin/users/edit-user/useEditUserDialog";

export default function EditUserDialog({
	user,
	disabled = false,
	onUpdated,
	onPasswordReset,
	temporaryPassword,
	onTemporaryPasswordChange,
}) {
	const {
		open,
		handleOpenChange,
		form,
		setPatch,
		error,
		branchesStatus,
		branchExistence,
		isSubmitting,
		effectiveDisabled,
		canSubmit,
		handleSubmit,
	} = useEditUserDialog({ user, disabled, onUpdated });

	// Defensive: if the row has no valid user object, do not render an action.
	if (!user || typeof user.id !== "string" || !user.id) return null;

	return (
		<Dialog open={open} onOpenChange={handleOpenChange}>
			<DialogTrigger asChild>
				<Button
					type="button"
					variant="outline"
					size="icon-sm"
					disabled={disabled}
					title="Benutzer bearbeiten"
					aria-label="Benutzer bearbeiten"
				>
					<Pencil className="h-4 w-4 text-amber-500 dark:text-amber-400" />
				</Button>
			</DialogTrigger>

			<DialogContent className="sm:max-w-xl">
				<DialogHeader>
					<DialogTitle>Benutzer bearbeiten</DialogTitle>
					<DialogDescription>
						Ändern Sie Benutzername, E-Mail, Rolle oder Niederlassung.
					</DialogDescription>
				</DialogHeader>

				<EditUserForm
					user={user}
					form={form}
					setPatch={setPatch}
					error={error}
					branchesStatus={branchesStatus}
					branchExistence={branchExistence}
					isSubmitting={isSubmitting}
					disabled={effectiveDisabled}
					canSubmit={canSubmit}
					temporaryPassword={temporaryPassword}
					onTemporaryPasswordChange={onTemporaryPasswordChange}
					onPasswordReset={onPasswordReset}
					onCancel={() => handleOpenChange(false)}
					onSubmit={handleSubmit}
				/>
			</DialogContent>
		</Dialog>
	);
}
