"use client"

import type { ICaptionResultStepProps } from "./CaptionResultStep.d"
import type { JSX } from "react"

import { MediaPlayer, MediaProvider } from "@vidstack/react"
import {
	defaultLayoutIcons,
	DefaultVideoLayout,
} from "@vidstack/react/player/layouts/default"

import "@vidstack/react/player/styles/default/theme.css"
import "@vidstack/react/player/styles/default/layouts/video.css"

import {
	Check,
	CheckCircle,
	Download,
	FileVideo,
	RefreshCw,
} from "lucide-react"
import { FunctionComponent, useMemo } from "react"

import cs from "classnames"

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

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

const SPARKLE_COUNT = 10

function formatFileSize(bytes: number): string {
	if (bytes < 1024) return `${bytes} Б`
	if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} КБ`
	if (bytes < 1024 * 1024 * 1024)
		return `${(bytes / (1024 * 1024)).toFixed(1)} МБ`
	return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} ГБ`
}

export const CaptionResultStep: FunctionComponent<ICaptionResultStepProps> = ({
	className,
}): JSX.Element => {
	const {
		captionedVideoFileId,
		markStepCompleted,
		reopenCaptionConfig,
	} = useWizard()

	const { data: fileInfo, isLoading } = api.useQuery(
		"get",
		"/api/files/files/{file_id}/resolve/",
		{ params: { path: { file_id: captionedVideoFileId ?? "" } } },
		{ enabled: !!captionedVideoFileId },
	)

	const videoUrl = fileInfo?.file_url ?? ""

	const handleDownload = () => {
		if (!videoUrl) return
		const link = document.createElement("a")
		link.href = videoUrl
		link.download = fileInfo?.filename ?? "captioned-video.mp4"
		link.click()
	}

	const handleRerender = () => {
		void reopenCaptionConfig()
	}

	const handleFinish = () => {
		markStepCompleted("caption-result")
	}

	const sparkles = useMemo(
		() =>
			Array.from({ length: SPARKLE_COUNT }, (_, i) => ({
				id: i,
				variant: i % 2 === 0 ? "green" : "purple",
				left: `${10 + (i * 80) / SPARKLE_COUNT + Math.sin(i * 1.7) * 5}%`,
				top: `${15 + Math.sin(i * 2.3) * 30 + 20}%`,
				delay: `${(i * 0.3) % 2.5}s`,
				size: 4 + (i % 3) * 2,
			})),
		[],
	)

	if (isLoading) {
		return (
			<div className={cs(styles.root, className)}>
				<p className={styles.loading}>Загрузка видео...</p>
			</div>
		)
	}

	return (
		<div className={cs(styles.root, className)} data-testid="CaptionResultStep">
			{/* Sparkle particles */}
			<div className={styles.sparkles} aria-hidden="true">
				{sparkles.map((s) => (
					<span
						key={s.id}
						className={cs(
							styles.sparkle,
							s.variant === "green"
								? styles.sparkleGreen
								: styles.sparklePurple,
						)}
						style={{
							left: s.left,
							top: s.top,
							animationDelay: s.delay,
							width: s.size,
							height: s.size,
						}}
					/>
				))}
			</div>

			{/* Content area */}
			<div className={styles.content}>
				{/* Success header */}
				<div className={styles.header}>
					<Badge variant="success">
						<CheckCircle size={14} />
						Готово
					</Badge>
					<h2 className={styles.title}>Результат</h2>
					<p className={styles.subtitle}>
						Видео с субтитрами готово к скачиванию
					</p>
				</div>

				{/* Video player */}
				<div className={styles.playerContainer}>
					<div className={styles.playerWrapper}>
						{videoUrl ? (
							<MediaPlayer
								src={videoUrl}
								crossOrigin=""
								playsInline
								className={styles.player}
							>
								<MediaProvider />
								<DefaultVideoLayout icons={defaultLayoutIcons} />
							</MediaPlayer>
						) : (
							<div className={styles.placeholder}>Видео недоступно</div>
						)}
					</div>
				</div>

				{/* File info bar */}
				{fileInfo?.filename && (
					<div className={styles.fileInfoContainer}>
						<div className={styles.fileInfoBar}>
							<FileVideo size={18} className={styles.fileIcon} />
							<span className={styles.fileName}>{fileInfo.filename}</span>
							{typeof fileInfo.file_size === "number" && (
								<span className={styles.fileSize}>
									{formatFileSize(fileInfo.file_size)}
								</span>
							)}
						</div>
					</div>
				)}
			</div>

			{/* Footer */}
			<div className={styles.footer}>
					<Button variant="ghost" onClick={handleRerender}>
						<RefreshCw size={16} />
						Перегенерировать
					</Button>
					<div className={styles.rightActions}>
						<Button variant="primary" onClick={handleDownload}>
						<Download size={16} />
						Скачать
					</Button>
						<Button variant="outline" onClick={handleFinish}>
							<Check size={16} />
							Завершить
						</Button>
					</div>
				</div>
			</div>
	)
}
