"use client"

import type { IProcessingStepProps } from "./ProcessingStep.d"
import type { JSX } from "react"

import cs from "classnames"
import { Info } from "lucide-react"
import { FunctionComponent } from "react"

import { useWizard } from "@shared/context/WizardContext"
import { useTaskProgressState } from "@shared/hooks/useTaskProgressState"
import { Button, CircularProgress } from "@shared/ui"

import {
	buildCancelJobPayload,
	useCancelJob,
} from "../useCancelJob"

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

const JOB_TYPE_LABELS: Record<string, string> = {
	SILENCE_DETECT: "АНАЛИЗ",
	SILENCE_APPLY: "ПРИМЕНЕНИЕ ВЫРЕЗОК",
	TRANSCRIPTION_GENERATE: "ТРАНСКРИБАЦИЯ",
	CAPTIONS_GENERATE: "ГЕНЕРАЦИЯ СУБТИТРОВ",
}

const JOB_TYPE_BACK_STEP_MAP = {
	SILENCE_APPLY: "fragments",
} as const

export const ProcessingStep: FunctionComponent<IProcessingStepProps> = ({
	className,
}): JSX.Element => {
	const { activeJobId, activeJobType, setActiveJob, goBack, goToStep } =
		useWizard()
	const { mutate: cancelJob, isPending: isCancelling } = useCancelJob()

	const navigateBack = () => {
		const targetStep = activeJobType
			? JOB_TYPE_BACK_STEP_MAP[
					activeJobType as keyof typeof JOB_TYPE_BACK_STEP_MAP
				]
			: null

		if (targetStep) {
			goToStep(targetStep)
			return
		}

		goBack()
	}

	const taskProgress = useTaskProgressState({
		jobId: activeJobId,
		enabled: !!activeJobId,
		defaultMessage: "Подождите, идёт обработка...",
	})

	const progressPct = taskProgress.progressPct
	const statusLabel = activeJobType
		? (JOB_TYPE_LABELS[activeJobType] ?? "ОБРАБОТКА")
		: "ОБРАБОТКА"
	const statusMessage = taskProgress.message
	const isFailed = taskProgress.status === "FAILED"

	const handleCancel = () => {
		if (!activeJobId || isCancelling) return

		cancelJob(buildCancelJobPayload(activeJobId), {
			onSuccess: () => {
				setActiveJob(null)
				navigateBack()
			},
		})
	}

	const handleFailedBack = () => {
		setActiveJob(null)
		navigateBack()
	}

	return (
		<div
			className={cs(styles.root, className)}
			data-testid="ProcessingStep"
		>
			<div className={styles.content}>
				<div className={styles.progressWrapper}>
					<CircularProgress
						percentage={progressPct}
						size={200}
						strokeWidth={8}
						color={
							isFailed
								? "var(--color-danger)"
								: "var(--color-success)"
						}
						className={styles.circle}
						bgClassName={styles.circleBg}
						valueClassName={styles.circleValue}
					/>
					<div className={styles.progressInner}>
						<span className={styles.percentage}>
							{Math.round(progressPct)}%
						</span>
						<span className={styles.statusLabel}>
							{isFailed ? "ОШИБКА" : statusLabel}
						</span>
					</div>
				</div>

				<p
					className={cs(styles.description, {
						[styles.descriptionError]: isFailed,
					})}
				>
					{isFailed
						? (taskProgress.errorMessage ??
							"Произошла ошибка при обработке")
						: statusMessage}
					</p>

				<div className={styles.infoCard}>
					<Info size={16} className={styles.infoIcon} />
					<span>
						Обработка выполняется на сервере. Вы можете покинуть
						страницу — прогресс сохранится.
					</span>
				</div>

				<Button
					variant={isFailed ? "outline" : "danger"}
					size="sm"
					onClick={isFailed ? handleFailedBack : handleCancel}
					disabled={isCancelling}
				>
					{isFailed
						? "Назад"
						: isCancelling
							? "Отмена..."
							: "Отменить обработку"}
				</Button>
			</div>
		</div>
	)
}
