"use client"

import type { ICaptionSettingsStepProps } from "./CaptionSettingsStep.d"
import type { components } from "@shared/api/__generated__/openapi.types"
import type { JSX } from "react"

import {
	FunctionComponent,
	useRef,
	useState,
} from "react"

import cs from "classnames"

import { useWizard } from "@shared/context/WizardContext"
import { Button } from "@shared/ui"

import { PresetGrid } from "./PresetGrid"
import { StyleEditor } from "./StyleEditor"
import styles from "./CaptionSettingsStep.module.scss"

type CaptionPresetRead = components["schemas"]["CaptionPresetRead"]

const ERROR_SUBMIT = "Не удалось запустить генерацию субтитров"

export const CaptionSettingsStep: FunctionComponent<
	ICaptionSettingsStepProps
> = ({ className }): JSX.Element => {
	const {
		captionPresetId,
		selectCaptionPreset,
		startCaptionRender,
		goBack,
	} = useWizard()

	const [activeTab, setActiveTab] = useState<"select" | "editor">("select")
	const [editingPreset, setEditingPreset] = useState<CaptionPresetRead | null>(
		null,
	)
	const [submitError, setSubmitError] = useState<string | null>(null)
	const [isSubmitting, setIsSubmitting] = useState(false)
	const submitLockRef = useRef(false)

	const handleGenerate = async () => {
		if (submitLockRef.current || isSubmitting) return
		if (!captionPresetId) return

		submitLockRef.current = true
		setSubmitError(null)
		setIsSubmitting(true)

		try {
			await startCaptionRender()
			submitLockRef.current = false
		} catch {
			submitLockRef.current = false
			setSubmitError(ERROR_SUBMIT)
		} finally {
			setIsSubmitting(false)
		}
	}

	const handleEdit = (preset: CaptionPresetRead) => {
		setEditingPreset(preset)
		setActiveTab("editor")
	}

	const handleCreateNew = () => {
		setEditingPreset(null)
		setActiveTab("editor")
	}

	const handleSaved = (presetId: string) => {
		void selectCaptionPreset(presetId)
		setActiveTab("select")
	}

	const handleSelectPreset = (presetId: string | null) => {
		void selectCaptionPreset(presetId)
	}

	if (activeTab === "editor") {
		return (
			<div
				className={cs(styles.root, className)}
				data-testid="CaptionSettingsStep"
			>
				<h2 className={styles.title}>Редактор стиля</h2>
				<StyleEditor
					initialConfig={editingPreset?.style_config}
					presetId={editingPreset?.id}
					presetName={editingPreset?.name}
					onSaved={handleSaved}
					onCancel={() => setActiveTab("select")}
				/>
			</div>
		)
	}

	return (
		<div
			className={cs(styles.root, className)}
			data-testid="CaptionSettingsStep"
		>
			<h2 className={styles.title}>Выбор пресета субтитров</h2>

			<div className={styles.scrollArea}>
				<PresetGrid
					selectedPresetId={captionPresetId}
					onSelect={handleSelectPreset}
					onEdit={handleEdit}
					onCreateNew={handleCreateNew}
				/>
			</div>

			{submitError && <p className={styles.error}>{submitError}</p>}

			<div className={styles.footer}>
				<Button variant="outline" onClick={goBack}>
					Назад
				</Button>
				<Button
					variant="primary"
					onClick={handleGenerate}
					disabled={!captionPresetId || isSubmitting}
				>
					{isSubmitting ? "Запуск..." : "Генерировать"}
				</Button>
			</div>
		</div>
	)
}
