"use client";

import {
	Button,
	Input,
	Label,
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
	Textarea,
} from "@mdxui/primitives";
import * as React from "react";
import type { Secret } from "./types";

interface SecretFormProps {
	secret?: Secret;
	environment: string;
	environments: string[];
	onSubmit: (secret: Omit<Secret, "id" | "createdAt" | "updatedAt">) => void;
	onCancel: () => void;
}

export function SecretForm({
	secret,
	environment: defaultEnvironment,
	environments,
	onSubmit,
	onCancel,
}: SecretFormProps) {
	const [key, setKey] = React.useState(secret?.key || "");
	const [value, setValue] = React.useState(secret?.value || "");
	const [description, setDescription] = React.useState(
		secret?.description || "",
	);
	const [environment, setEnvironment] = React.useState(
		secret?.environment || defaultEnvironment,
	);

	const handleSubmit = (e: React.FormEvent) => {
		e.preventDefault();

		if (!key.trim() || !value.trim()) return;

		onSubmit({
			key: key.trim(),
			value: value.trim(),
			description: description.trim() || undefined,
			environment,
		});
	};

	return (
		<form onSubmit={handleSubmit} className="space-y-4">
			<div className="space-y-2">
				<Label htmlFor="key">Key *</Label>
				<Input
					id="key"
					placeholder="DATABASE_URL"
					value={key}
					onChange={(e) =>
						setKey(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, "_"))
					}
					required
					autoFocus
				/>
				<p className="text-xs text-muted-foreground">
					Use UPPER_CASE with underscores (e.g., API_KEY, DATABASE_URL)
				</p>
			</div>

			<div className="space-y-2">
				<Label htmlFor="value">Value *</Label>
				<Textarea
					id="value"
					placeholder="Enter secret value"
					value={value}
					onChange={(e) => setValue(e.target.value)}
					rows={3}
					required
					className="font-mono"
				/>
			</div>

			<div className="space-y-2">
				<Label htmlFor="environment">Environment *</Label>
				<Select value={environment} onValueChange={setEnvironment}>
					<SelectTrigger id="environment">
						<SelectValue />
					</SelectTrigger>
					<SelectContent>
						{environments.map((env) => (
							<SelectItem key={env} value={env}>
								{env.charAt(0).toUpperCase() + env.slice(1)}
							</SelectItem>
						))}
					</SelectContent>
				</Select>
			</div>

			<div className="space-y-2">
				<Label htmlFor="description">Description</Label>
				<Textarea
					id="description"
					placeholder="Optional description of this secret"
					value={description}
					onChange={(e) => setDescription(e.target.value)}
					rows={2}
				/>
			</div>

			<div className="flex justify-end gap-2">
				<Button type="button" variant="outline" onClick={onCancel}>
					Cancel
				</Button>
				<Button type="submit" disabled={!key.trim() || !value.trim()}>
					{secret ? "Update" : "Create"} Secret
				</Button>
			</div>
		</form>
	);
}
