import { useMemo } from "react";
import { Link } from "react-router-dom";

import { Icon } from "../../icon";
import type { Session } from "../../../api/sessions";
import type { IconName } from "../../../utils/icons";
import type { ProjectWithRepos, RepositorySummary } from "../../../types";
import { openSession } from "../../../utils/open-session";

interface ProjectListItemProps {
	project: ProjectWithRepos;
	deleteConfirm: boolean;
	onEdit: () => void;
	onDelete: () => void;
	onConfirmDelete: () => void;
	onCancelDelete: () => void;
	onAddRepository?: () => void;
	sessions: Session[];
}

export const ProjectListItem = ({
	project,
	deleteConfirm,
	onEdit,
	onDelete,
	onConfirmDelete,
	onCancelDelete,
	onAddRepository,
	sessions,
}: ProjectListItemProps) => {
	return (
		<article className="project-list-item">
			<header className="project-list-item-header">
				<div className="project-list-item-title">
					<h3>{project.name}</h3>
					{project.description && (
						<p className="muted">{project.description}</p>
					)}
				</div>
				<div className="project-list-item-actions">
					{deleteConfirm ? (
						<div className="delete-confirm">
							<span>Are you sure?</span>
							<button
								className="btn btn-sm btn-danger"
								onClick={onConfirmDelete}
								type="button"
							>
								<Icon name="delete" size="sm" /> Delete
							</button>
							<button
								className="btn btn-sm btn-secondary"
								onClick={onCancelDelete}
								type="button"
							>
								<Icon name="cancel" size="sm" /> Cancel
							</button>
						</div>
					) : (
						<>
							<button
								className="btn btn-sm btn-secondary"
								onClick={onEdit}
								type="button"
							>
								<Icon name="edit" size="sm" /> Edit
							</button>
							<button
								className="btn btn-sm btn-danger"
								onClick={onDelete}
								type="button"
							>
								<Icon name="delete" size="sm" /> Delete
							</button>
						</>
					)}
				</div>
			</header>

			<div className="project-repo-list">
				{project.repositories.map((repo) => (
					<ProjectRepoItem
						key={repo.id}
						repo={repo}
						project={project}
						sessions={sessions}
					/>
				))}
				{onAddRepository && (
					<button
						type="button"
						className="project-repo-item project-add-repo-card"
						onClick={onAddRepository}
					>
						<Icon name="add" size="md" />
						<span className="project-repo-name">Add Repository</span>
					</button>
				)}
			</div>
		</article>
	);
};

function ProjectRepoItem({
	repo,
	project,
	sessions,
}: {
	repo: RepositorySummary;
	project: ProjectWithRepos;
	sessions: Session[];
}) {
	const sessionsByWorkspace = useMemo(() => {
		const map = new Map<string, Session[]>();
		for (const ws of repo.workspaces) {
			map.set(ws.name, []);
		}
		for (const session of sessions) {
			if (
				session.project_id !== project.id ||
				session.repository_id !== repo.id
			) {
				continue;
			}
			if (session.status !== "running") continue;
			const list = map.get(session.workspace_name || "") || [];
			list.push(session);
			map.set(session.workspace_name || "", list);
		}
		return map;
	}, [sessions, project.id, repo.id, repo.workspaces]);

	const branch = useMemo(() => {
		const firstWs = repo.workspaces[0];
		if (!firstWs) return "—";
		return firstWs.branch;
	}, [repo.workspaces]);

	return (
		<div className="project-repo-item">
			<div className="project-repo-item-header">
				<Icon name="folder" size="sm" />
				<span className="project-repo-name">{repo.name}</span>
				<span className="project-repo-branch">
					<Icon name="branch" size="sm" /> {branch}
				</span>
			</div>

			<div className="project-repo-workspaces">
				{repo.workspaces.length === 0 ? (
					<p className="muted text-sm">No workspaces.</p>
				) : (
					repo.workspaces.map((ws) => {
						const runningSessions = sessionsByWorkspace.get(ws.name) || [];
						return (
							<div key={ws.id} className="project-repo-workspace">
								<Link className="workspace-name" to={`/workspaces/${ws.id}`}>
									{ws.name}
								</Link>
								{runningSessions.length === 0 ? (
									<span className="muted text-xs">No running tools</span>
								) : (
									<ul className="workspace-tool-list">
										{runningSessions.map((session) => (
											<li key={session.id}>
												<SessionToolLink session={session} />
											</li>
										))}
									</ul>
								)}
							</div>
						);
					})
				)}
			</div>
		</div>
	);
}

function SessionToolLink({ session }: { session: Session }) {
	return (
		<button
			type="button"
			onClick={() => openSession(session)}
			className="workspace-tool-link"
			title={`${session.display_name} (${session.status})`}
		>
			<span
				className={`session-status-dot ${session.status === "running" ? "running" : ""}`}
			/>
			<Icon name={(session.tool_icon as IconName) || "terminal"} size="sm" />
			<span className="tool-name">
				{session.display_name || session.tool_type_name}
			</span>
		</button>
	);
}
