import { useState } from "react";
import { Link } from "react-router-dom";
import { EmptyState, ErrorState, LoadingState } from "../components/data-states";
import { useMobileViewport } from "../hooks/use-mobile-viewport";
import { useRepoWorkspace } from "../hooks/use-repo-workspace";
import { WorkspaceHeader } from "../components/features/workspace/workspace-header";
import { WorkspaceLayout } from "../components/features/workspace/WorkspaceLayout";

type MobileTab = "files" | "editor" | "git" | "terminal";

export const RepoWorkspace = () => {
	const {
		projectId,
		project,
		status,
		repositories,
		selectedRepoId,
		selectedRepo,
		branches,
		currentBranch,
		gitStatus,
		toolTypes,
		handleRepoChange,
		handleBranchChange,
		loadGitStatus,
		loadBranches,
		loadRepositories,
	} = useRepoWorkspace();
	const isMobile = useMobileViewport();
	const [mobileTab, setMobileTab] = useState<MobileTab>("files");

	return (
		<section className="repo-workspace">
			{project && (
				<WorkspaceHeader
					project={project}
					currentRepo={selectedRepo || null}
				/>
			)}

			{status === "loading" && (
				<LoadingState message="Loading repositories..." />
			)}

			{status === "error" && (
				<ErrorState
					message="Failed to load repositories"
					onRetry={() => void loadRepositories()}
				/>
			)}

			{status === "empty" && (
				<div className="card stack">
					<EmptyState message="No repositories in this project yet." />
					<Link
						className="primary-button"
						to={`/projects/${projectId}/settings/repositories`}
					>
						Manage Repositories
					</Link>
				</div>
			)}

			{status === "ready" && repositories.length > 0 && (
				<WorkspaceLayout
					projectId={projectId!}
					project={project}
					isMobile={isMobile}
					mobileTab={mobileTab}
					selectedRepoId={selectedRepoId}
					selectedRepo={selectedRepo}
					branches={branches}
					currentBranch={currentBranch}
					gitStatus={gitStatus}
					toolTypes={toolTypes}
					repositories={repositories}
					onMobileTabChange={setMobileTab}
					onRepoChange={handleRepoChange}
					onBranchChange={handleBranchChange}
					onRefresh={() => {
						void loadBranches();
						void loadGitStatus();
						window.dispatchEvent(new CustomEvent("refresh-file-tree"));
					}}
				/>
			)}
		</section>
	);
};
