/** Files tab for the workspace detail page. */

import { useState } from "react";
import { Icon } from "../../icon";
import { useWorkspaceFiles } from "../../../hooks/use-workspace-files";
import { useWorkspaceGit } from "../../../hooks/use-workspace-git";
import type { FileEntry } from "../../../api/workspace-files";

interface WorkspaceFilePanelProps {
	workspaceId: string;
}

export function WorkspaceFilePanel({ workspaceId }: WorkspaceFilePanelProps) {
	const {
		entries,
		content,
		currentPath,
		loadFile,
		saveFile,
		loading,
		error,
		navigateTo,
	} = useWorkspaceFiles(workspaceId);
	const { status, commit, push, pull, fetch } = useWorkspaceGit(workspaceId);
	const [selectedPath, setSelectedPath] = useState<string | null>(null);
	const [editContent, setEditContent] = useState<string | null>(null);
	const [isEditing, setIsEditing] = useState(false);
	const [commitMessage, setCommitMessage] = useState("");

	const handleSelect = (entry: FileEntry) => {
		if (entry.type === "directory") {
			setSelectedPath(null);
			setIsEditing(false);
			setEditContent(null);
			navigateTo(entry.path);
			return;
		}
		setSelectedPath(entry.path);
		setIsEditing(false);
		setEditContent(null);
		loadFile(entry.path);
	};

	const navigateUp = () => {
		if (!currentPath) return;
		const parentPath = currentPath.split("/").slice(0, -1).join("/");
		navigateTo(parentPath);
		setSelectedPath(null);
		setIsEditing(false);
		setEditContent(null);
	};

	const handleEdit = () => {
		if (content !== null) {
			setEditContent(content);
			setIsEditing(true);
		}
	};

	const handleSave = async () => {
		if (selectedPath && editContent !== null) {
			await saveFile(selectedPath, editContent, commitMessage || undefined);
			setIsEditing(false);
			setCommitMessage("");
		}
	};

	return (
		<div className="files-tab">
			{status && (
				<div className="git-toolbar">
					<div className="git-toolbar-status">
						{status.modified.length > 0 && (
							<span className="status-modified">
								M {status.modified.length}
							</span>
						)}
						{status.added.length > 0 && (
							<span className="status-added">A {status.added.length}</span>
						)}
						{status.deleted.length > 0 && (
							<span className="status-deleted">D {status.deleted.length}</span>
						)}
						{status.untracked.length > 0 && (
							<span className="status-untracked">
								? {status.untracked.length}
							</span>
						)}
					</div>
					<div className="git-toolbar-actions">
						<input
							type="text"
							value={commitMessage}
							onChange={(e) => setCommitMessage(e.target.value)}
							placeholder="Commit message"
						/>
						<button
							onClick={() => commit(commitMessage)}
							disabled={!commitMessage}
							type="button"
						>
							Commit
						</button>
						<button onClick={push} type="button">
							Push
						</button>
						<button onClick={pull} type="button">
							Pull
						</button>
						<button onClick={fetch} type="button">
							Fetch
						</button>
					</div>
				</div>
			)}
			<div className="files-split">
				<div className="file-tree">
					{currentPath && (
						<button
							className="tree-entry tree-up"
							onClick={navigateUp}
							type="button"
						>
							<Icon name="folder" size="sm" /> ..
						</button>
					)}
					{loading && <p className="muted">Loading...</p>}
					{error && <p className="error-text">{error}</p>}
					{entries.map((entry) => (
						<button
							key={entry.path}
							className={`tree-entry ${entry.type} ${selectedPath === entry.path ? "selected" : ""}`}
							onClick={() => handleSelect(entry)}
							type="button"
						>
							<Icon
								name={entry.type === "directory" ? "folder" : "file"}
								size="sm"
							/>
							{entry.name}
						</button>
					))}
				</div>
				<div className="file-viewer">
					{selectedPath ? (
						<>
							<div className="file-viewer-header">
								<span>{selectedPath}</span>
								{!isEditing && (
									<button onClick={handleEdit} type="button">
										Edit
									</button>
								)}
							</div>
							{isEditing ? (
								<>
									<textarea
										className="file-editor"
										value={editContent || ""}
										onChange={(e) => setEditContent(e.target.value)}
									/>
									<div className="file-editor-actions">
										<button onClick={() => setIsEditing(false)} type="button">
											Cancel
										</button>
										<button onClick={handleSave} type="button">
											Save
										</button>
									</div>
								</>
							) : (
								<pre className="file-content">{content || "Loading..."}</pre>
							)}
						</>
					) : (
						<p className="muted">Select a file to view</p>
					)}
				</div>
			</div>
		</div>
	);
}
