"use client"

import type { ISilenceSettingsModalProps } from "./SilenceSettingsModal.d"
import type { JSX } from "react"

import { FunctionComponent, useEffect } from "react"
import { Controller, useForm } from "react-hook-form"

import api from "@shared/api"
import { Button, Form, Modal, Select, SelectItem } from "@shared/ui"

import { useSubmitSilenceDetect } from "./useSubmitSilenceDetect"
import styles from "./SilenceSettingsModal.module.scss"

interface ISilenceSettingsFormData {
	file_key: string
	min_silence_duration_ms: number
	silence_threshold_db: number
	padding_ms: number
}

const DEFAULT_MIN_SILENCE_MS = 200
const DEFAULT_THRESHOLD_DB = 16
const DEFAULT_PADDING_MS = 100

export const SilenceSettingsModal: FunctionComponent<
	ISilenceSettingsModalProps
> = ({ projectId, open, onOpenChange }): JSX.Element => {
	const { control, handleSubmit, reset, watch, setValue } =
		useForm<ISilenceSettingsFormData>({
			defaultValues: {
				file_key: "",
				min_silence_duration_ms: DEFAULT_MIN_SILENCE_MS,
				silence_threshold_db: DEFAULT_THRESHOLD_DB,
				padding_ms: DEFAULT_PADDING_MS,
			},
		})

	const minSilence = watch("min_silence_duration_ms")
	const threshold = watch("silence_threshold_db")
	const padding = watch("padding_ms")

	const { data: files } = api.useQuery("get", "/api/files/files/", {
		queryKey: ["files", projectId],
	})

	const projectFiles = (files ?? []).filter(
		(f) => f.project_id === projectId && !f.is_deleted,
	)

	const { mutate, isPending } = useSubmitSilenceDetect({
		onSuccess: () => {
			onOpenChange?.(false)
		},
		onError: (error) => {
			console.error("Silence detect submit failed:", error)
		},
	})

	useEffect(() => {
		if (!open) reset()
	}, [open, reset])

	const onSubmit = (data: ISilenceSettingsFormData): void => {
		// Body shape matches SilenceDetectRequest — types available after gen:api-types
		;(mutate as (args: { body: Record<string, unknown> }) => void)({
			body: {
				file_key: data.file_key,
				project_id: projectId,
				min_silence_duration_ms: data.min_silence_duration_ms,
				silence_threshold_db: data.silence_threshold_db,
				padding_ms: data.padding_ms,
			},
		})
	}

	return (
		<Modal
			open={open}
			onOpenChange={onOpenChange}
			title="Удалить тишину"
			description="Выберите файл и настройте параметры обнаружения тишины"
		>
			<div className={styles.root} data-testid="SilenceSettingsModal">
				<Form onSubmit={handleSubmit(onSubmit)}>
					<div className={styles.fields}>
						<div className={styles.selectField}>
							<div className={styles.selectLabel}>Файл</div>
							<Controller
								name="file_key"
								control={control}
								rules={{ required: "Выберите файл" }}
								render={({ field }) => (
									<Select
										value={field.value}
										onValueChange={field.onChange}
										placeholder="Выберите файл"
									>
										{projectFiles.map((f) => (
											<SelectItem key={f.id} value={f.path}>
												{f.original_filename}
											</SelectItem>
										))}
									</Select>
								)}
							/>
						</div>

						<div className={styles.rangeField}>
							<div className={styles.rangeLabel}>
								<span>Мин. длительность тишины</span>
								<span className={styles.rangeValue}>{minSilence} мс</span>
							</div>
							<input
								type="range"
								className={styles.rangeInput}
								min={100}
								max={2000}
								step={50}
								value={minSilence}
								onChange={(e) =>
									setValue(
										"min_silence_duration_ms",
										Number(e.target.value),
									)
								}
							/>
						</div>

						<div className={styles.rangeField}>
							<div className={styles.rangeLabel}>
								<span>Порог тишины</span>
								<span className={styles.rangeValue}>{threshold} дБ</span>
							</div>
							<input
								type="range"
								className={styles.rangeInput}
								min={6}
								max={40}
								step={2}
								value={threshold}
								onChange={(e) =>
									setValue("silence_threshold_db", Number(e.target.value))
								}
							/>
						</div>

						<div className={styles.rangeField}>
							<div className={styles.rangeLabel}>
								<span>Отступ</span>
								<span className={styles.rangeValue}>{padding} мс</span>
							</div>
							<input
								type="range"
								className={styles.rangeInput}
								min={0}
								max={500}
								step={25}
								value={padding}
								onChange={(e) =>
									setValue("padding_ms", Number(e.target.value))
								}
							/>
						</div>
					</div>

					<div className={styles.actions}>
						<Button
							type="button"
							variant="outline"
							disabled={isPending}
							onClick={() => onOpenChange?.(false)}
						>
							Отмена
						</Button>
						<Button type="submit" variant="primary" disabled={isPending}>
							Запустить
						</Button>
					</div>
				</Form>
			</div>
		</Modal>
	)
}
