import { useState } from "react";

import { MobileListView } from "../mobile/mobile-list-view";
import { MobileDetailView } from "../mobile/mobile-detail-view";
import { MobileEditView } from "../mobile/mobile-edit-view";
import { MobileFAB } from "../mobile/mobile-fab";
import { ManifestEditor } from "../tool/manifest-editor";
import { Icon } from "../../icon";
import type { ToolType } from "../../../api/tool-types";
import type { ToolTypeFormState } from "./ToolTypeEditorPanel";
import type { ToolDefinitionManifest } from "../../../api/tool-definitions";

export type MobileView = "list" | "detail" | "edit";

interface ToolWorkshopMobileViewProps {
	toolTypes: ToolType[];
	selectedToolType: ToolType | null;
	mobileView: MobileView;
	isCreating: boolean;
	toolTypeForm: ToolTypeFormState;
	manifestData: Record<string, unknown> | null;
	manifestDefinitionId: string | null;
	baseDefinitions: ToolDefinitionManifest[];
	toolTypeError: string | null;
	toolTypeDirty: boolean;
	onViewChange: (view: MobileView) => void;
	onSelect: (toolType: ToolType) => void;
	onCreate: () => void;
	onDelete: (id: string) => void;
	onFormChange: (changes: Partial<ToolTypeFormState>) => void;
	onManifestChange: (manifest: Record<string, unknown> | null) => void;
	onSubmit: (e?: React.FormEvent) => Promise<boolean>;
	onCancel: () => void;
}

export const ToolWorkshopMobileView = ({
	toolTypes,
	selectedToolType,
	mobileView,
	isCreating,
	toolTypeForm,
	manifestData,
	manifestDefinitionId,
	baseDefinitions,
	toolTypeError,
	toolTypeDirty,
	onViewChange,
	onSelect,
	onCreate,
	onDelete,
	onFormChange,
	onManifestChange,
	onSubmit,
	onCancel,
}: ToolWorkshopMobileViewProps) => {
	const [isSaving, setIsSaving] = useState(false);

	const handleSave = async () => {
		setIsSaving(true);
		try {
			const ok = await onSubmit();
			if (ok) {
				onViewChange(isCreating ? "list" : "edit");
			}
		} finally {
			setIsSaving(false);
		}
	};

	const handleDelete = () => {
		if (selectedToolType) {
			void onDelete(selectedToolType.id);
			onViewChange("list");
		}
	};

	if (mobileView === "list") {
		return (
			<div className="mobile-page">
				<div className="mobile-page-header">
					<h1>Tool Workshop</h1>
					<span className="muted">{toolTypes.length} tool types</span>
				</div>
				<MobileListView
					items={toolTypes.map((t) => ({
						id: t.id,
						title: t.display_name,
						subtitle: `${t.category || "Uncategorized"} · ${t.definition_type} · ${t.interface_type === "web" ? `Port ${t.default_port}` : "Terminal"}`,
					}))}
					onItemClick={(id) => {
						const toolType = toolTypes.find((t) => t.id === id);
						if (toolType) {
							onSelect(toolType);
							onViewChange("edit");
						}
					}}
					onItemDelete={(id) => onDelete(id)}
					emptyMessage="No tool types yet"
				/>
				<MobileFAB
					onClick={() => {
						onCreate();
						onViewChange("edit");
					}}
				/>
			</div>
		);
	}

	if (mobileView === "detail" && selectedToolType) {
		const fields = [
			{ label: "Name", value: selectedToolType.name },
			{ label: "Display Name", value: selectedToolType.display_name },
			{ label: "Description", value: selectedToolType.description },
			{ label: "Category", value: selectedToolType.category },
			{ label: "Interface Type", value: selectedToolType.interface_type },
			{
				label: "Requires Port",
				value: selectedToolType.requires_port,
				type: "boolean" as const,
			},
			...(selectedToolType.requires_port
				? [{ label: "Default Port", value: selectedToolType.default_port }]
				: []),
			{
				label: "Definition Type",
				value: selectedToolType.definition_type,
			},
			{
				label: "Startup Command",
				value: selectedToolType.startup_command,
			},
			{
				label: "Readiness Command",
				value: selectedToolType.readiness_probe?.command ?? null,
			},
			{
				label: "Readiness Timeout",
				value: selectedToolType.readiness_probe?.timeout ?? null,
			},
			{
				label: "Readiness Interval",
				value: selectedToolType.readiness_probe?.interval ?? null,
			},
			{
				label: "Required Variables",
				value: selectedToolType.required_variables?.join(", ") ?? null,
			},
			...(selectedToolType.definition_type !== "manifest"
				? [
						{
							label:
								selectedToolType.definition_type === "compose"
									? "Compose Template"
									: "Dockerfile Template",
							value:
								selectedToolType.definition_type === "compose"
									? selectedToolType.compose_template
									: selectedToolType.dockerfile_template,
							type: "code" as const,
						},
					]
				: []),
		];

		return (
			<MobileDetailView
				title={selectedToolType.display_name}
				subtitle={`${selectedToolType.name} · ${selectedToolType.definition_type}`}
				fields={fields}
				onEdit={() => {
					onViewChange("edit");
				}}
				onDelete={handleDelete}
				onBack={() => {
					onViewChange("list");
				}}
			/>
		);
	}

	if (mobileView === "edit") {
		const templateValue =
			toolTypeForm.definition_type === "compose"
				? toolTypeForm.compose_template
				: toolTypeForm.dockerfile_template;

		return (
			<MobileEditView
				title={isCreating ? "Create Tool Type" : "Edit Tool Type"}
				onCancel={onCancel}
				onSave={handleSave}
				onDelete={isCreating ? undefined : handleDelete}
				deleteLabel="Delete Tool Type"
				isSaving={isSaving}
			>
				<div className="mobile-form-group">
					<label className="mobile-form-label">Definition Type</label>
					<select
						value={toolTypeForm.definition_type}
						onChange={(e) =>
							onFormChange({
								definition_type: e.target.value as
									| "compose"
									| "dockerfile"
									| "manifest",
							})
						}
						className="mobile-form-select"
						disabled={!isCreating}
					>
						<option value="compose">Docker Compose</option>
						<option value="dockerfile">Dockerfile</option>
						<option value="manifest">Manifest (Declarative)</option>
					</select>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Name *</label>
					<input
						type="text"
						value={toolTypeForm.name}
						onChange={(e) => onFormChange({ name: e.target.value })}
						className="mobile-form-input"
						placeholder="e.g., my-tool"
						disabled={!isCreating}
						required
					/>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Display Name *</label>
					<input
						type="text"
						value={toolTypeForm.display_name}
						onChange={(e) => onFormChange({ display_name: e.target.value })}
						className="mobile-form-input"
						placeholder="e.g., My Tool"
						required
					/>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Description</label>
					<textarea
						value={toolTypeForm.description}
						onChange={(e) => onFormChange({ description: e.target.value })}
						className="mobile-form-textarea"
						placeholder="What does this tool do?"
						rows={3}
					/>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Category</label>
					<input
						type="text"
						value={toolTypeForm.category}
						onChange={(e) => onFormChange({ category: e.target.value })}
						className="mobile-form-input"
						placeholder="e.g., development"
					/>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Interface Type</label>
					<select
						value={toolTypeForm.interface_type}
						onChange={(e) => {
							const value = e.target.value as "web" | "terminal";
							onFormChange({
								interface_type: value,
								requires_port: value === "web",
								default_port: value === "web" ? toolTypeForm.default_port : "",
							});
						}}
						className="mobile-form-select"
					>
						<option value="web">Web</option>
						<option value="terminal">Terminal</option>
					</select>
				</div>

				<div className="mobile-form-group mobile-form-row">
					<label className="mobile-form-label mobile-form-checkbox-label">
						<input
							type="checkbox"
							checked={toolTypeForm.requires_port}
							onChange={(e) =>
								onFormChange({ requires_port: e.target.checked })
							}
							className="mobile-form-checkbox"
						/>
						Requires Port
					</label>
				</div>

				{toolTypeForm.requires_port && (
					<div className="mobile-form-group">
						<label className="mobile-form-label">Default Port *</label>
						<input
							type="number"
							value={toolTypeForm.default_port}
							onChange={(e) =>
								onFormChange({ default_port: e.target.value })
							}
							className="mobile-form-input"
							placeholder="e.g., 8080"
							required
						/>
					</div>
				)}

				{toolTypeForm.interface_type === "terminal" && (
					<div className="mobile-form-group">
						<label className="mobile-form-label">Startup Command</label>
						<input
							type="text"
							value={toolTypeForm.startup_command}
							onChange={(e) =>
								onFormChange({ startup_command: e.target.value })
							}
							className="mobile-form-input"
							placeholder="Command to run on startup"
						/>
						<small className="mobile-form-help">
							Command to run before the interactive shell for each new
							terminal session.
						</small>
					</div>
				)}

				{toolTypeForm.definition_type === "manifest" ? (
					<div className="mobile-manifest-editor-wrapper">
						<ManifestEditor
							manifest={manifestData}
							baseDefinitions={baseDefinitions}
							onChange={(m) => onManifestChange(m)}
							definitionId={manifestDefinitionId}
						/>
					</div>
				) : (
					<div className="mobile-form-group">
						<label className="mobile-form-label">
							{toolTypeForm.definition_type === "compose"
								? "Compose Template *"
								: "Dockerfile Template *"}
						</label>
						<textarea
							value={templateValue}
							onChange={(e) => {
								if (toolTypeForm.definition_type === "compose") {
									onFormChange({ compose_template: e.target.value });
								} else {
									onFormChange({ dockerfile_template: e.target.value });
								}
							}}
							className="mobile-form-textarea mobile-form-code"
							placeholder={
								toolTypeForm.definition_type === "compose"
									? "version: '3'"
									: "FROM ubuntu:22.04"
							}
							rows={10}
							required
						/>
					</div>
				)}

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

				<div className="mobile-form-group">
					<label className="mobile-form-label">Readiness Timeout (seconds)</label>
					<input
						type="number"
						value={toolTypeForm.readiness_timeout}
						onChange={(e) =>
							onFormChange({ readiness_timeout: e.target.value })
						}
						className="mobile-form-input"
						placeholder="30"
					/>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Readiness Interval (seconds)</label>
					<input
						type="number"
						value={toolTypeForm.readiness_interval}
						onChange={(e) =>
							onFormChange({ readiness_interval: e.target.value })
						}
						className="mobile-form-input"
						placeholder="2"
					/>
				</div>

				<div className="mobile-form-group">
					<label className="mobile-form-label">Required Variables</label>
					<input
						type="text"
						value={toolTypeForm.required_variables}
						onChange={(e) =>
							onFormChange({ required_variables: e.target.value })
						}
						className="mobile-form-input"
						placeholder="VAR1, VAR2, VAR3"
					/>
				</div>

				{toolTypeError && (
					<p className="mobile-form-error">
						<Icon name="warning" size="sm" /> {toolTypeError}
					</p>
				)}

				{toolTypeDirty && (
					<button
						type="button"
						className="secondary-button mobile-discard-button"
						onClick={onCancel}
						disabled={isSaving}
					>
						Discard Changes
					</button>
				)}
			</MobileEditView>
		);
	}

	return (
		<div className="mobile-page">
			<div className="mobile-page-header">
				<h1>Tool Workshop</h1>
				<span className="muted">{toolTypes.length} tool types</span>
			</div>
			<MobileListView
				items={toolTypes.map((t) => ({
					id: t.id,
					title: t.display_name,
					subtitle: `${t.category || "Uncategorized"} · ${t.definition_type} · ${t.interface_type === "web" ? `Port ${t.default_port}` : "Terminal"}`,
				}))}
				onItemClick={(id) => {
					const toolType = toolTypes.find((t) => t.id === id);
					if (toolType) {
						onSelect(toolType);
						onViewChange("edit");
					}
				}}
				onItemDelete={(id) => onDelete(id)}
				emptyMessage="No tool types yet"
			/>
			<MobileFAB
				onClick={() => {
					onCreate();
					onViewChange("edit");
				}}
			/>
		</div>
	);
};
