import { Trash2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "../../components/ui/button";
import { useFieldContext } from ".";
import { FieldErrors } from "./Errors.Field";

type DynamicInputField = {
	name?: string;
	label: string;
	inputType: "text" | "email" | "password" | "number" | "username";
	required?: boolean;
	description?: string;
	addLabel?: string;
	placeholder?: string;
	disabled?: boolean;
};

const autoCompleteMap: Record<string, string> = {
	email: "email",
	password: "current-password",
	text: "off",
	username: "username",
};

export const DynamicInputField = ({
	label,
	inputType = "text",
	required = false,
	description,
	addLabel,
}: DynamicInputField) => {
	const field = useFieldContext<any>();
	const values = Array.isArray(field.state.value) ? field.state.value : [];

	return (
		<div className="grid gap-3 mt-2">
			<div className="flex items-start justify-between gap-4">
				<div className="space-y-1">
					<Label>{label}</Label>
					{description ? (
						<p className="text-sm text-muted-foreground">{description}</p>
					) : null}
				</div>

				<Button
					type="button"
					variant="secondary"
					onClick={() => {
						field.pushValue("");
					}}
				>
					{addLabel}
				</Button>
			</div>
			<div className="grid gap-3">
				{values.map((_: string, index: number) => (
					<div key={`${field.name}-${index}`} className="grid gap-2">
						<div className="flex items-center gap-2">
							<Label htmlFor={field.name}>{label}</Label>
							<Input
								id={field.name}
								autoComplete={autoCompleteMap[inputType] ?? "off"}
								value={field.state.value?.[index] ?? ""}
								onChange={(e) => field.replaceValue(index, e.target.value)}
								onBlur={field.handleBlur}
								type={inputType}
								required={required}
							/>
							{values.length > 1 ? (
								<Button
									type="button"
									size={"icon"}
									variant="destructive"
									onClick={() => field.removeValue(index)}
								>
									<Trash2 className="w-32 h-32" />
								</Button>
							) : null}
							<FieldErrors meta={field.state.meta} />
						</div>
					</div>
				))}
			</div>
		</div>
	);
};
