"use client"

import type { ISubtitleRevisionStepProps } from "./SubtitleRevisionStep.d"
import type { JSX } from "react"

import {
	MediaPlayer,
	MediaProvider,
	type MediaPlayerInstance,
} from "@vidstack/react"
import {
	DefaultVideoLayout,
	defaultLayoutIcons,
} from "@vidstack/react/player/layouts/default"
import "@vidstack/react/player/styles/default/theme.css"
import "@vidstack/react/player/styles/default/layouts/video.css"
import cs from "classnames"
import { FunctionComponent, useEffect, useRef } from "react"

import api from "@shared/api"
import { useWorkspaceFiles } from "@shared/context/WorkspaceContext"
import { useWizard } from "@shared/context/WizardContext"
import { Button } from "@shared/ui"
import { TranscriptionEditor } from "@features/project"
import { TimelinePanel } from "@widgets/TimelinePanel"

import styles from "./SubtitleRevisionStep.module.scss"

/**
 * Auto-initializes WorkspaceContext with the video file
 * and transcription artifact so TimelinePanel and
 * TranscriptionEditor work correctly.
 */
const WorkspaceInit: FunctionComponent<{
	fileKey: string | null
	transcriptionArtifactId: string | null
}> = ({ fileKey, transcriptionArtifactId }) => {
	const { selectedFile, setSelectedFile, addUsedFile } = useWorkspaceFiles()

	useEffect(() => {
		if (!fileKey) return

		addUsedFile({
			id: fileKey,
			path: fileKey,
			source: "file",
			mimeType: "video/mp4",
			displayName: "Видео",
			iconType: "video",
		})

		if (!selectedFile) {
			setSelectedFile({
				id: fileKey,
				path: fileKey,
				source: "file",
				mimeType: "video/mp4",
			})
		}
	}, [fileKey, addUsedFile, setSelectedFile, selectedFile])

	useEffect(() => {
		if (!transcriptionArtifactId) return

		addUsedFile({
			id: transcriptionArtifactId,
			path: "transcription",
			source: "artifact",
			artifactType: "TRANSCRIPTION_JSON",
			displayName: "Субтитры",
			iconType: "text",
		})
	}, [transcriptionArtifactId, addUsedFile])

	return null
}

const SubtitleRevisionContent: FunctionComponent<{
	className?: string
}> = ({ className }) => {
	const {
		projectId,
		videoUrl,
		primaryFileKey,
		transcriptionArtifactId,
		goBack,
		markTranscriptionReviewed,
	} = useWizard()
	const isArtifactResolving = false
	const isTranscriptionReady = Boolean(transcriptionArtifactId)
	const isTranscriptionUnavailable =
		!isTranscriptionReady && !isArtifactResolving

	// Auto-trigger frame extraction so video frames appear in timeline
	const frameExtractMutation = api.useMutation(
		"post",
		"/api/tasks/frame-extract/",
	)
	const extractTriggeredRef = useRef(false)
	const playerRef = useRef<MediaPlayerInstance | null>(null)

	useEffect(() => {
		if (!primaryFileKey || !projectId || extractTriggeredRef.current) return
		extractTriggeredRef.current = true
		frameExtractMutation.mutate({
			body: {
				file_key: primaryFileKey,
				project_id: projectId,
				regenerate: false,
			},
		})
	}, [primaryFileKey, projectId]) // eslint-disable-line react-hooks/exhaustive-deps

	const handleFinish = () => {
		if (!isTranscriptionReady) return
		void markTranscriptionReviewed()
	}

	return (
		<div
			className={cs(styles.root, className)}
			data-testid="SubtitleRevisionStep"
		>
			<WorkspaceInit
				fileKey={primaryFileKey}
				transcriptionArtifactId={transcriptionArtifactId}
			/>

			<div className={styles.workspaceShell}>
				<div className={styles.mainGrid}>
					<section className={cs(styles.panel, styles.editorPanel)}>
						<div className={styles.panelHeader}>
							<h2 className={styles.panelTitle}>Текст</h2>
						</div>
						<div
							className={styles.editorColumn}
							aria-busy={isArtifactResolving}
						>
							{isArtifactResolving ? (
								<div
									className={styles.placeholder}
									role="status"
									aria-live="polite"
									aria-atomic="true"
								>
									Загружаем субтитры...
								</div>
							) : transcriptionArtifactId ? (
								<TranscriptionEditor artifactId={transcriptionArtifactId} />
							) : (
								<div
									className={styles.placeholder}
									role="status"
									aria-live="polite"
									aria-atomic="true"
								>
									Транскрипция не найдена
								</div>
							)}
						</div>
					</section>

					<section className={cs(styles.panel, styles.playerPanel)}>
						<div className={styles.panelHeader}>
							<h2 className={styles.panelTitle}>Видео</h2>
						</div>
						<div className={styles.playerColumn}>
							{videoUrl ? (
								<MediaPlayer
									ref={playerRef}
									src={videoUrl}
									crossOrigin=""
									playsInline
									className={styles.mediaPlayer}
								>
									<MediaProvider />
									<DefaultVideoLayout
										icons={defaultLayoutIcons}
										disableTimeSlider
										slots={{
											timeSlider: null,
											currentTime: null,
											timeDivider: null,
											endTime: null,
											startDuration: null,
											seekBackwardButton: null,
											seekForwardButton: null,
											captionButton: null,
											settingsMenu: null,
											pipButton: null,
											airPlayButton: null,
											googleCastButton: null,
											downloadButton: null,
										}}
									/>
								</MediaPlayer>
							) : (
								<div className={styles.placeholder}>
									Видео недоступно
								</div>
							)}
						</div>
					</section>
				</div>

				<div className={styles.timelineWrapper}>
					<TimelinePanel
						projectId={projectId}
						audioUrl={videoUrl}
						className={styles.timeline}
						playerRef={playerRef}
					/>
				</div>

				<div className={styles.footer}>
					<Button variant="outline" onClick={goBack}>
						Отмена
					</Button>
					<Button
						variant="primary"
						onClick={handleFinish}
						loading={isArtifactResolving}
						disabled={!isTranscriptionReady}
					>
						{isArtifactResolving
							? "Проверяем..."
							: isTranscriptionUnavailable
								? "Субтитры не найдены"
								: "Далее"}
					</Button>
				</div>
			</div>
		</div>
	)
}

export const SubtitleRevisionStep: FunctionComponent<
	ISubtitleRevisionStepProps
> = ({ className }): JSX.Element => {
	return <SubtitleRevisionContent className={className} />
}
