"use client"

import type { JSX } from "react"

import { useParams } from "next/navigation"
import { FunctionComponent } from "react"

import api from "@shared/api"
import { useBreadcrumbs } from "@shared/context/BreadcrumbsContext"
import {
	useWorkspaceFiles,
	WorkspaceProvider,
} from "@shared/context/WorkspaceContext"
import { TranscriptionEditor } from "@features/project"
import {
	ActionPanel,
	FileTree,
	VideoPlayer,
	WorkspaceLayout,
} from "@widgets/Workspace"

import { IProjectWorkspacePageProps } from "./ProjectWorkspacePage.d"
import styles from "./ProjectWorkspacePage.module.scss"

/* ------------------------------------------------------------------ */
/*  Inner wrapper — resolves which viewer to show based on selection    */
/* ------------------------------------------------------------------ */

const WorkspaceViewer: FunctionComponent<{ projectId: string }> = ({
	projectId,
}) => {
	const { selectedFile } = useWorkspaceFiles()

	if (selectedFile?.artifactType === "TRANSCRIPTION_JSON") {
		return <TranscriptionEditor artifactId={selectedFile.id} />
	}

	return <VideoPlayer projectId={projectId} />
}

/* ------------------------------------------------------------------ */
/*  Page                                                               */
/* ------------------------------------------------------------------ */

export const ProjectWorkspacePage: FunctionComponent<
	IProjectWorkspacePageProps
> = (): JSX.Element => {
	const params = useParams<{ project_id: string }>()
	const projectId = params?.project_id ?? ""

	const { data: project } = api.useQuery("get", "/api/projects/{project_id}/", {
		params: { path: { project_id: projectId } },
	})

	useBreadcrumbs([
		{ label: "Проекты", href: "/projects" },
		{ label: project?.name ?? "..." },
	])

	return (
		<WorkspaceProvider projectId={projectId}>
			<div className={styles.root} data-testid="ProjectWorkspacePage">
				<WorkspaceLayout
					fileTree={<FileTree projectId={projectId} />}
					player={<WorkspaceViewer projectId={projectId} />}
					actionPanel={<ActionPanel projectId={projectId} />}
				/>
			</div>
		</WorkspaceProvider>
	)
}
