"use client"

import type { ISegmentSplitterProps } from "./SegmentSplitter.d"
import type { JSX } from "react"

import { FunctionComponent, useCallback, useMemo, useState } from "react"

import {
	type EditorSegment,
	splitSegmentAtMarkers,
} from "@shared/lib/transcriptionDocument"

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

export const SegmentSplitter: FunctionComponent<ISegmentSplitterProps> = ({
	segment,
	onSplit,
	onCancel,
}): JSX.Element => {
	const [markers, setMarkers] = useState<Set<number>>(new Set())

	const words = segment.words!

	const toggleMarker = useCallback((idx: number) => {
		setMarkers((prev) => {
			const next = new Set(prev)
			if (next.has(idx)) {
				next.delete(idx)
			} else {
				next.add(idx)
			}
			return next
		})
	}, [])

	const preview: EditorSegment[] = useMemo(() => {
		if (markers.size === 0) return [segment]
		return splitSegmentAtMarkers(segment, Array.from(markers))
	}, [segment, markers])

	const handleSplit = useCallback(() => {
		if (markers.size === 0) return
		onSplit(preview)
	}, [markers, preview, onSplit])

	return (
		<div className={styles.root} data-testid="SegmentSplitter">
			<div className={styles.wordsRow}>
				{words.map((word, idx) => (
					<span key={idx} className={styles.wordGroup}>
						{idx > 0 && (
							<button
								className={`${styles.gap} ${markers.has(idx) ? styles.active : ""}`}
								onClick={() => toggleMarker(idx)}
								title="Разделить здесь"
								type="button"
							/>
						)}
						<span className={styles.word}>{word.text}</span>
					</span>
				))}
			</div>

			{markers.size > 0 && (
				<div className={styles.preview}>
					<span className={styles.previewLabel}>Результат:</span>
					{preview.map((seg, idx) => (
						<div key={idx} className={styles.previewSegment}>
							<span className={styles.previewTime}>
								{seg.startTime} — {seg.endTime}
							</span>
							<span className={styles.previewText}>{seg.text}</span>
						</div>
					))}
				</div>
			)}

			<div className={styles.actions}>
				<button
					className={styles.splitBtn}
					onClick={handleSplit}
					disabled={markers.size === 0}
					type="button"
				>
					Разделить
				</button>
				<button className={styles.cancelBtn} onClick={onCancel} type="button">
					Отмена
				</button>
			</div>
		</div>
	)
}
