"use client"

import type { ITranscriptionModalProps } from "./TranscriptionModal.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 { useSubmitTranscription } from "./useSubmitTranscription"
import styles from "./TranscriptionModal.module.scss"

interface ITranscriptionFormData {
	file_key: string
	engine: "whisper" | "google" | "salutespeech"
	language: string
	model: string
}

const ENGINE_OPTIONS = [
	{ value: "whisper", label: "Whisper (локальный)" },
	{ value: "google", label: "Google Speech" },
	{ value: "salutespeech", label: "SaluteSpeech" },
]

const LANGUAGE_OPTIONS = [
	{ value: "auto", label: "Авто" },
	{ value: "ru", label: "Русский" },
	{ value: "en", label: "Английский" },
]

const WHISPER_MODEL_OPTIONS = [
	{ value: "base", label: "Базовая" },
	{ value: "small", label: "Малая" },
	{ value: "medium", label: "Средняя" },
	{ value: "large", label: "Большая" },
]

const SALUTE_MODEL_OPTIONS = [
	{ value: "general", label: "Общая" },
	{ value: "finance", label: "Финансы" },
	{ value: "medicine", label: "Медицина" },
]

export const TranscriptionModal: FunctionComponent<
	ITranscriptionModalProps
> = ({ projectId, open, onOpenChange }): JSX.Element => {
	const { control, handleSubmit, reset, watch, setValue } =
		useForm<ITranscriptionFormData>({
			defaultValues: {
				file_key: "",
				engine: "whisper",
				language: "auto",
				model: "base",
			},
		})

	const engine = watch("engine")

	useEffect(() => {
		if (engine === "salutespeech") {
			setValue("model", "general")
		} else if (engine === "whisper") {
			setValue("model", "base")
		}
	}, [engine, setValue])

	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 } = useSubmitTranscription({
		onSuccess: () => {
			onOpenChange?.(false)
		},
		onError: (error) => {
			console.error("Transcription submit failed:", error)
		},
	})

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

	const onSubmit = (data: ITranscriptionFormData): void => {
		mutate({
			body: {
				file_key: data.file_key,
				project_id: projectId,
				engine: data.engine,
				language: data.language === "auto" ? undefined : data.language,
				model: data.model,
			},
		})
	}

	return (
		<Modal
			open={open}
			onOpenChange={onOpenChange}
			title="Создать транскрипцию"
			description="Выберите файл и параметры транскрипции"
		>
			<div className={styles.root} data-testid="TranscriptionModal">
				<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.selectField}>
							<div className={styles.selectLabel}>Движок</div>
							<Controller
								name="engine"
								control={control}
								render={({ field }) => (
									<Select
										value={field.value}
										onValueChange={field.onChange}
										placeholder="Выберите движок"
									>
										{ENGINE_OPTIONS.map((opt) => (
											<SelectItem key={opt.value} value={opt.value}>
												{opt.label}
											</SelectItem>
										))}
									</Select>
								)}
							/>
						</div>

						<div className={styles.selectField}>
							<div className={styles.selectLabel}>Язык</div>
							<Controller
								name="language"
								control={control}
								render={({ field }) => (
									<Select
										value={field.value}
										onValueChange={field.onChange}
										placeholder="Выберите язык"
									>
										{LANGUAGE_OPTIONS.map((opt) => (
											<SelectItem key={opt.value} value={opt.value}>
												{opt.label}
											</SelectItem>
										))}
									</Select>
								)}
							/>
						</div>

						{(engine === "whisper" || engine === "salutespeech") && (
							<div className={styles.selectField}>
								<div className={styles.selectLabel}>Модель</div>
								<Controller
									name="model"
									control={control}
									render={({ field }) => (
										<Select
											value={field.value}
											onValueChange={field.onChange}
											placeholder="Выберите модель"
										>
											{(engine === "whisper"
												? WHISPER_MODEL_OPTIONS
												: SALUTE_MODEL_OPTIONS
											).map((opt) => (
												<SelectItem key={opt.value} value={opt.value}>
													{opt.label}
												</SelectItem>
											))}
										</Select>
									)}
								/>
							</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>
	)
}
