import * as React from "react";
import type { BotConfig } from "../api/bot_config";
import { botConfigApi } from "../api/bot_config";

const { useState, useEffect } = React;

interface BotConfigPageProps {
	onBack: () => void;
}

const fieldStyle: React.CSSProperties = {
	display: "flex",
	flexDirection: "column",
	gap: "4px",
};

const labelStyle: React.CSSProperties = {
	fontSize: "0.8em",
	color: "#aaa",
	fontWeight: 500,
};

const inputStyle: React.CSSProperties = {
	padding: "8px 10px",
	borderRadius: "6px",
	border: "1px solid #333",
	background: "#1e1e1e",
	color: "#ececec",
	fontSize: "0.9em",
	fontFamily: "monospace",
	outline: "none",
};

const sectionStyle: React.CSSProperties = {
	background: "#1e1e1e",
	border: "1px solid #333",
	borderRadius: "8px",
	padding: "20px",
	display: "flex",
	flexDirection: "column",
	gap: "14px",
};

const sectionTitleStyle: React.CSSProperties = {
	fontSize: "0.85em",
	fontWeight: 600,
	color: "#aaa",
	textTransform: "uppercase",
	letterSpacing: "0.06em",
	marginBottom: "2px",
};

function Field({
	label,
	value,
	onChange,
	placeholder,
	type = "text",
}: {
	label: string;
	value: string;
	onChange: (v: string) => void;
	placeholder?: string;
	type?: string;
}) {
	return (
		<div style={fieldStyle}>
			<label style={labelStyle}>{label}</label>
			<input
				type={type}
				value={value}
				onChange={(e) => onChange(e.target.value)}
				placeholder={placeholder}
				style={inputStyle}
				autoComplete="off"
			/>
		</div>
	);
}

function ListField({
	label,
	value,
	onChange,
	placeholder,
}: {
	label: string;
	value: string[];
	onChange: (v: string[]) => void;
	placeholder?: string;
}) {
	return (
		<div style={fieldStyle}>
			<label style={labelStyle}>{label} (one per line)</label>
			<textarea
				value={value.join("\n")}
				onChange={(e) =>
					onChange(e.target.value.split("\n").filter((s) => s.trim()))
				}
				placeholder={placeholder}
				rows={3}
				style={{ ...inputStyle, resize: "vertical" }}
			/>
		</div>
	);
}

/// Bot configuration page — form for Matrix and Slack credentials.
export function BotConfigPage({ onBack }: BotConfigPageProps) {
	const [transport, setTransport] = useState<"matrix" | "slack">("matrix");
	const [enabled, setEnabled] = useState(false);
	const [homeserver, setHomeserver] = useState("");
	const [username, setUsername] = useState("");
	const [password, setPassword] = useState("");
	const [roomIds, setRoomIds] = useState<string[]>([]);
	const [slackBotToken, setSlackBotToken] = useState("");
	const [slackSigningSecret, setSlackSigningSecret] = useState("");
	const [slackChannelIds, setSlackChannelIds] = useState<string[]>([]);
	const [status, setStatus] = useState<"idle" | "saving" | "saved" | "error">(
		"idle",
	);
	const [errorMsg, setErrorMsg] = useState<string | null>(null);

	useEffect(() => {
		botConfigApi
			.getConfig()
			.then((cfg) => {
				if (cfg.transport === "slack") setTransport("slack");
				setEnabled(cfg.enabled ?? false);
				setHomeserver(cfg.homeserver ?? "");
				setUsername(cfg.username ?? "");
				setPassword(cfg.password ?? "");
				setRoomIds(cfg.room_ids ?? []);
				setSlackBotToken(cfg.slack_bot_token ?? "");
				setSlackSigningSecret(cfg.slack_signing_secret ?? "");
				setSlackChannelIds(cfg.slack_channel_ids ?? []);
			})
			.catch(() => {});
	}, []);

	function buildConfig(): BotConfig {
		return {
			transport,
			enabled,
			homeserver: homeserver || null,
			username: username || null,
			password: password || null,
			room_ids: roomIds.length > 0 ? roomIds : null,
			slack_bot_token: slackBotToken || null,
			slack_signing_secret: slackSigningSecret || null,
			slack_channel_ids: slackChannelIds.length > 0 ? slackChannelIds : null,
		};
	}

	async function handleSave() {
		setStatus("saving");
		setErrorMsg(null);
		try {
			await botConfigApi.saveConfig(buildConfig());
			setStatus("saved");
			setTimeout(() => setStatus("idle"), 2000);
		} catch (e) {
			setStatus("error");
			setErrorMsg(e instanceof Error ? e.message : "Save failed");
		}
	}

	return (
		<div
			style={{
				display: "flex",
				flexDirection: "column",
				height: "100%",
				backgroundColor: "#171717",
				color: "#ececec",
				overflow: "auto",
			}}
		>
			<div
				style={{
					padding: "12px 24px",
					borderBottom: "1px solid #333",
					display: "flex",
					alignItems: "center",
					gap: "16px",
					background: "#171717",
					flexShrink: 0,
				}}
			>
				<button
					type="button"
					onClick={onBack}
					style={{
						background: "transparent",
						border: "none",
						cursor: "pointer",
						color: "#888",
						fontSize: "0.9em",
						padding: "4px 8px",
						borderRadius: "4px",
					}}
				>
					← Back
				</button>
				<span style={{ fontWeight: 700, fontSize: "1em" }}>
					Bot Configuration
				</span>
			</div>

			<div
				style={{
					flex: 1,
					padding: "24px",
					display: "flex",
					flexDirection: "column",
					gap: "20px",
					maxWidth: "600px",
				}}
			>
				<div style={sectionStyle}>
					<div style={sectionTitleStyle}>General</div>

					<div style={fieldStyle}>
						<label style={labelStyle}>Transport</label>
						<select
							value={transport}
							onChange={(e) =>
								setTransport(e.target.value as "matrix" | "slack")
							}
							style={{ ...inputStyle, cursor: "pointer" }}
						>
							<option value="matrix">Matrix</option>
							<option value="slack">Slack</option>
						</select>
					</div>

					<label
						style={{
							display: "flex",
							alignItems: "center",
							gap: "8px",
							cursor: "pointer",
							fontSize: "0.9em",
							color: "#ccc",
						}}
					>
						<input
							type="checkbox"
							checked={enabled}
							onChange={(e) => setEnabled(e.target.checked)}
						/>
						Enabled
					</label>
				</div>

				{transport === "matrix" && (
					<div style={sectionStyle}>
						<div style={sectionTitleStyle}>Matrix Credentials</div>
						<Field
							label="Homeserver"
							value={homeserver}
							onChange={setHomeserver}
							placeholder="https://matrix.example.com"
						/>
						<Field
							label="Username"
							value={username}
							onChange={setUsername}
							placeholder="@botname:example.com"
						/>
						<Field
							label="Password"
							value={password}
							onChange={setPassword}
							placeholder="bot password"
							type="password"
						/>
						<ListField
							label="Room IDs"
							value={roomIds}
							onChange={setRoomIds}
							placeholder="!roomid:example.com"
						/>
					</div>
				)}

				{transport === "slack" && (
					<div style={sectionStyle}>
						<div style={sectionTitleStyle}>Slack Credentials</div>
						<Field
							label="Bot Token"
							value={slackBotToken}
							onChange={setSlackBotToken}
							placeholder="xoxb-..."
						/>
						<Field
							label="Signing Secret"
							value={slackSigningSecret}
							onChange={setSlackSigningSecret}
							placeholder="signing secret"
							type="password"
						/>
						<ListField
							label="Channel IDs"
							value={slackChannelIds}
							onChange={setSlackChannelIds}
							placeholder="C01ABCDEF"
						/>
					</div>
				)}

				<div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
					<button
						type="button"
						onClick={handleSave}
						disabled={status === "saving"}
						style={{
							padding: "8px 24px",
							borderRadius: "6px",
							border: "none",
							background: status === "saved" ? "#1a5c2a" : "#2563eb",
							color: "#fff",
							cursor: status === "saving" ? "not-allowed" : "pointer",
							fontSize: "0.9em",
							fontWeight: 600,
							opacity: status === "saving" ? 0.7 : 1,
						}}
					>
						{status === "saving"
							? "Saving..."
							: status === "saved"
								? "Saved!"
								: "Save"}
					</button>
					{status === "error" && errorMsg && (
						<span style={{ color: "#f08080", fontSize: "0.85em" }}>
							{errorMsg}
						</span>
					)}
				</div>
			</div>
		</div>
	);
}
