"use client";

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

import BranchNumberInput from "@/components/admin/users/BranchNumberInput";
import UserTemporaryPasswordField from "@/components/admin/users/UserTemporaryPasswordField";
import { EDIT_ROLE_OPTIONS } from "@/components/admin/users/edit-user/editUserUtils";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
import { DialogFooter } from "@/components/ui/dialog";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuLabel,
	DropdownMenuRadioGroup,
	DropdownMenuRadioItem,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

function RoleSelect({ value, onChange, disabled }) {
	const label =
		EDIT_ROLE_OPTIONS.find((x) => x.value === value)?.label || "Rolle wählen";

	return (
		<div className="grid gap-2">
			<Label>Rolle</Label>

			<DropdownMenu>
				<DropdownMenuTrigger asChild>
					<Button type="button" variant="outline" disabled={disabled}>
						{label}
					</Button>
				</DropdownMenuTrigger>

				<DropdownMenuContent align="start" className="min-w-56">
					<DropdownMenuLabel>Rolle auswählen</DropdownMenuLabel>
					<DropdownMenuSeparator />

					<DropdownMenuRadioGroup value={value} onValueChange={onChange}>
						{EDIT_ROLE_OPTIONS.map((opt) => (
							<DropdownMenuRadioItem key={opt.value} value={opt.value}>
								{opt.label}
							</DropdownMenuRadioItem>
						))}
					</DropdownMenuRadioGroup>
				</DropdownMenuContent>
			</DropdownMenu>
		</div>
	);
}

export default function EditUserForm({
	user,
	form,
	setPatch,
	error,
	branchesStatus,
	branchExistence,
	disabled,
	isSubmitting,
	canSubmit,
	temporaryPassword,
	onTemporaryPasswordChange,
	onPasswordReset,
	onCancel,
	onSubmit,
}) {
	const role = String(form?.role || "branch");
	const userId = String(user?.id || "");
	const branchMessageId = "eu-branch-message";
	const showUnknownBranch =
		role === "branch" && Boolean(branchExistence?.hasUnknownBranch);
	const showFailOpenNote = role === "branch" && Boolean(branchExistence?.listError);
	const showBranchLoading =
		role === "branch" && !showUnknownBranch && branchesStatus === "loading";

	return (
		<form onSubmit={onSubmit} className="space-y-4">
			{error ? (
				<Alert variant="destructive">
					<AlertTitle>{error.title}</AlertTitle>
					{error.description ? (
						<AlertDescription>{error.description}</AlertDescription>
					) : null}

					{Array.isArray(error.hints) && error.hints.length > 0 ? (
						<AlertDescription>
							<ul className="mt-2 list-disc pl-5">
								{error.hints.map((line) => (
									<li key={line}>{line}</li>
								))}
							</ul>
						</AlertDescription>
					) : null}
				</Alert>
			) : null}

			<div className="grid gap-2">
				<Label>User ID</Label>
				<Input value={userId || "—"} disabled />
			</div>

			<div className="grid gap-3 md:grid-cols-2">
				<div className="grid gap-2">
					<Label htmlFor="eu-username">Benutzername</Label>
					<Input
						id="eu-username"
						value={form?.username ?? ""}
						onChange={(e) => setPatch({ username: e.target.value })}
						disabled={disabled}
						autoCapitalize="none"
						autoCorrect="off"
						spellCheck={false}
						placeholder="z. B. branchuser"
					/>
				</div>

				<div className="grid gap-2">
					<Label htmlFor="eu-email">E-Mail</Label>
					<Input
						id="eu-email"
						value={form?.email ?? ""}
						onChange={(e) => setPatch({ email: e.target.value })}
						disabled={disabled}
						placeholder="name@firma.de"
					/>
				</div>
			</div>

			<div className="grid gap-3 md:grid-cols-2">
				<RoleSelect
					value={role}
					onChange={(v) => setPatch({ role: v })}
					disabled={disabled}
				/>

				{role === "branch" ? (
					<div className="grid gap-2">
						<BranchNumberInput
							id="eu-branch"
							branchId={form?.branchId ?? ""}
							onBranchIdChange={(branchId) => setPatch({ branchId })}
							disabled={disabled}
							invalid={showUnknownBranch}
							describedBy={showUnknownBranch ? branchMessageId : undefined}
						/>

						{showUnknownBranch ? (
							<p id={branchMessageId} className="text-xs text-destructive">
								Diese Niederlassung ist nicht in der aktuellen Liste vorhanden.
							</p>
						) : null}

						{showFailOpenNote ? (
							<p className="text-xs text-muted-foreground">
								Hinweis: Die Niederlassungsliste konnte nicht geladen werden.
								Die Existenz kann aktuell nicht geprüft werden.
							</p>
						) : null}

						{showBranchLoading ? (
							<p className="text-xs text-muted-foreground">
								Niederlassungsliste wird geladen…
							</p>
						) : null}
					</div>
				) : (
					<div className="grid gap-2">
						<Label>Niederlassung</Label>
						<Input value="—" disabled />
					</div>
				)}
			</div>

			<div className="flex items-start gap-3 rounded-lg border p-3">
				<Checkbox
					checked={Boolean(form?.mustChangePassword)}
					disabled={disabled}
					onCheckedChange={(v) => {
						setPatch({ mustChangePassword: Boolean(v) });
					}}
				/>
				<div className="grid gap-1">
					<p className="text-sm font-medium">Passwortwechsel erforderlich</p>
					<p className="text-xs text-muted-foreground">
						Wenn aktiviert, muss der Benutzer beim nächsten Login sein Passwort
						ändern.
					</p>
				</div>
			</div>

			<div className="grid gap-2">
				<Label>Temporäres Passwort</Label>
				<UserTemporaryPasswordField
					user={user}
					temporaryPassword={temporaryPassword}
					onTemporaryPasswordChange={onTemporaryPasswordChange}
					onPasswordReset={onPasswordReset}
					disabled={disabled}
				/>
			</div>

			<DialogFooter>
				<Button
					type="button"
					variant="outline"
					disabled={disabled}
					onClick={onCancel}
				>
					Abbrechen
				</Button>

				<Button type="submit" disabled={disabled || !canSubmit}>
					{isSubmitting ? (
						<>
							<Loader2 className="h-4 w-4 animate-spin" />
							Speichern…
						</>
					) : (
						"Speichern"
					)}
				</Button>
			</DialogFooter>
		</form>
	);
}
