import { Icon } from "../../icon";
import { ManifestEditor } from "../tool/manifest-editor";
import type { ToolType } from "../../../api/tool-types";
import type { ToolDefinitionManifest } from "../../../api/tool-definitions";

export interface ToolTypeFormState {
	name: string;
	display_name: string;
	description: string;
	category: string;
	interface_type: "web" | "terminal";
	requires_port: boolean;
	default_port: string;
	definition_type: "compose" | "dockerfile" | "manifest";
	compose_template: string;
	dockerfile_template: string;
	readiness_command: string;
	readiness_timeout: string;
	readiness_interval: string;
	required_variables: string;
	startup_command: string;
}

interface ToolTypeEditorPanelProps {
	isCreating: boolean;
	selectedToolType: ToolType | null;
	form: ToolTypeFormState;
	manifestData: Record<string, unknown> | null;
	manifestDefinitionId: string | null;
	baseDefinitions: ToolDefinitionManifest[];
	toolTypeError: string | null;
	toolTypeDirty: boolean;
	onFormChange: (changes: Partial<ToolTypeFormState>) => void;
	onManifestChange: (manifest: Record<string, unknown> | null) => void;
	onSubmit: (e: React.FormEvent) => void;
	onReset: () => void;
}

export const ToolTypeEditorPanel = ({
	isCreating,
	selectedToolType,
	form,
	manifestData,
	manifestDefinitionId,
	baseDefinitions,
	toolTypeError,
	toolTypeDirty,
	onFormChange,
	onManifestChange,
	onSubmit,
	onReset,
}: ToolTypeEditorPanelProps) => {
	const hasSelection = isCreating || selectedToolType;

	return (
		<div style={{ flex: 1, overflow: "auto", padding: "1.5rem", minWidth: 0 }}>
			{!hasSelection ? (
				<div
					style={{
						textAlign: "center",
						paddingTop: "4rem",
						color: "var(--muted)",
					}}
				>
					<div style={{ opacity: 0.3, marginBottom: "1rem" }}>
						<Icon name="code" size="lg" />
					</div>
					<h3 style={{ margin: "0 0 0.5rem 0", fontWeight: 500 }}>
						Select a tool type
					</h3>
					<p style={{ margin: 0 }}>
						Choose a tool from the list to edit, or create a new one.
					</p>
				</div>
			) : (
				<div>
					<div style={{ marginBottom: "1.5rem" }}>
						<h1 style={{ margin: "0 0 0.5rem 0", fontSize: "1.5rem" }}>
							{isCreating
								? "Create Tool Type"
								: selectedToolType?.display_name}
						</h1>
						{!isCreating && (
							<p className="muted" style={{ margin: 0 }}>
								{selectedToolType?.name} · {selectedToolType?.definition_type}{" "}
								·{" "}
								{selectedToolType?.interface_type === "web"
									? `Port ${selectedToolType?.default_port}`
									: "Terminal"}
							</p>
						)}
					</div>

					<form
						onSubmit={onSubmit}
						className="stack"
						style={{ gap: "1rem", maxWidth: "800px" }}
					>
						<div className="form-group">
							<label htmlFor="definition-type">Definition Type</label>
							<select
								id="definition-type"
								value={form.definition_type}
								onChange={(e) => {
									onFormChange({
										definition_type: e.target.value as
											| "compose"
											| "dockerfile"
											| "manifest",
									});
								}}
								className="form-input"
								disabled={!isCreating}
							>
								<option value="compose">Docker Compose</option>
								<option value="dockerfile">Dockerfile</option>
								<option value="manifest">Manifest (Declarative)</option>
							</select>
						</div>

						<div className="row" style={{ gap: "1rem" }}>
							<div className="form-group" style={{ flex: 1 }}>
								<label htmlFor="tool-type-name">Name *</label>
								<input
									id="tool-type-name"
									type="text"
									value={form.name}
									onChange={(e) => {
										onFormChange({ name: e.target.value });
									}}
									disabled={!isCreating}
									placeholder="e.g., code-server"
									className="form-input"
									required
								/>
							</div>
							<div className="form-group" style={{ flex: 1 }}>
								<label htmlFor="tool-type-display-name">
									Display Name *
								</label>
								<input
									id="tool-type-display-name"
									type="text"
									value={form.display_name}
									onChange={(e) => {
										onFormChange({ display_name: e.target.value });
									}}
									placeholder="e.g., VS Code Server"
									className="form-input"
									required
								/>
							</div>
						</div>

						<div className="form-group">
							<label htmlFor="tool-type-description">Description</label>
							<input
								id="tool-type-description"
								type="text"
								value={form.description}
								onChange={(e) => {
									onFormChange({ description: e.target.value });
								}}
								placeholder="Optional description"
								className="form-input"
							/>
						</div>

						<div className="row" style={{ gap: "1rem" }}>
							<div className="form-group" style={{ flex: 1 }}>
								<label htmlFor="tool-type-category">Category</label>
								<input
									id="tool-type-category"
									type="text"
									value={form.category}
									onChange={(e) => {
										onFormChange({ category: e.target.value });
									}}
									placeholder="e.g., editor, notebook, ai-assistant"
									className="form-input"
								/>
							</div>
							<div className="form-group" style={{ flex: 1 }}>
								<label htmlFor="tool-type-interface">Interface Type</label>
								<select
									id="tool-type-interface"
									value={form.interface_type}
									onChange={(e) => {
										const value = e.target.value as "web" | "terminal";
										onFormChange({
											interface_type: value,
											requires_port: value === "web",
											default_port:
												value === "web" ? form.default_port : "",
										});
									}}
									className="form-input"
								>
									<option value="web">Web</option>
									<option value="terminal">Terminal</option>
								</select>
							</div>
						</div>

						{form.interface_type === "terminal" && (
							<div className="form-group">
								<label htmlFor="tool-type-startup-command">
									Startup Command
								</label>
								<input
									id="tool-type-startup-command"
									type="text"
									value={form.startup_command}
									onChange={(e) => {
										onFormChange({ startup_command: e.target.value });
									}}
									placeholder="e.g., cd /workspace && ls"
									className="form-input"
								/>
								<small className="form-help">
									Command to run before the interactive shell for each new
									terminal session.
								</small>
							</div>
						)}

						{form.requires_port && (
							<div className="form-group">
								<label htmlFor="tool-type-default-port">
									Default Port *
								</label>
								<input
									id="tool-type-default-port"
									type="number"
									value={form.default_port}
									onChange={(e) => {
										onFormChange({ default_port: e.target.value });
									}}
									placeholder="e.g., 8443"
									className="form-input"
									required
								/>
							</div>
						)}

						{form.definition_type === "manifest" ? (
							<ManifestEditor
								manifest={manifestData}
								baseDefinitions={baseDefinitions}
								onChange={(m) => {
									onManifestChange(m);
								}}
								definitionId={manifestDefinitionId}
							/>
						) : (
							<div className="form-group">
								<label htmlFor="tool-type-template">
									{form.definition_type === "compose"
										? "Compose Template"
										: "Dockerfile"}{" "}
									*
								</label>
								<textarea
									id="tool-type-template"
									value={
										form.definition_type === "compose"
											? form.compose_template
											: form.dockerfile_template
									}
									onChange={(e) => {
										if (form.definition_type === "compose") {
											onFormChange({ compose_template: e.target.value });
										} else {
											onFormChange({ dockerfile_template: e.target.value });
										}
									}}
									rows={12}
									placeholder={
										form.definition_type === "compose"
											? "version: '3.8'\nservices:\n  app:\n    image: ..."
											: "FROM node:18\nWORKDIR /app\n..."
									}
									className="form-input"
									style={{
										fontFamily: "monospace",
										fontSize: "0.875rem",
									}}
									required
								/>
							</div>
						)}

						<div className="form-group">
							<label htmlFor="readiness-command">
								Readiness Probe Command
							</label>
							<input
								id="readiness-command"
								type="text"
								value={form.readiness_command}
								onChange={(e) => {
									onFormChange({ readiness_command: e.target.value });
								}}
								placeholder="e.g., curl -f http://localhost:8080"
								className="form-input"
							/>
						</div>

						<div className="row" style={{ gap: "1rem" }}>
							<div className="form-group" style={{ flex: 1 }}>
								<label htmlFor="readiness-timeout">Timeout (seconds)</label>
								<input
									id="readiness-timeout"
									type="number"
									value={form.readiness_timeout}
									onChange={(e) => {
										onFormChange({ readiness_timeout: e.target.value });
									}}
									className="form-input"
								/>
							</div>
							<div className="form-group" style={{ flex: 1 }}>
								<label htmlFor="readiness-interval">
									Interval (seconds)
								</label>
								<input
									id="readiness-interval"
									type="number"
									value={form.readiness_interval}
									onChange={(e) => {
										onFormChange({ readiness_interval: e.target.value });
									}}
									className="form-input"
								/>
							</div>
						</div>

						<div className="form-group">
							<label>Required Variables (comma-separated)</label>
							<input
								type="text"
								value={form.required_variables}
								onChange={(e) => {
									onFormChange({ required_variables: e.target.value });
								}}
								placeholder="REPO_PATH, TOOL_NAME"
								className="form-input"
							/>
						</div>

						{toolTypeError && <p className="text-error">{toolTypeError}</p>}

						<div className="dialog-actions" style={{ marginTop: "1rem" }}>
							<button type="submit">
								<Icon name={isCreating ? "add" : "save"} size="sm" />
								{isCreating ? "Create Tool Type" : "Save Changes"}
							</button>
							{toolTypeDirty && (
								<button
									type="button"
									onClick={onReset}
									className="button-secondary"
								>
									<Icon name="cancel" size="sm" /> Discard
								</button>
							)}
						</div>
					</form>
				</div>
			)}
		</div>
	);
};
