"use client"

import type { IEditProjectModalProps } from "./EditProjectModal.d"
import type { JSX } from "react"

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

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

import { useUpdateProject } from "./useUpdateProject"
import styles from "./EditProjectModal.module.scss"

interface IEditProjectFormData {
	name: string
	description?: string
	language: string
}

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

export const EditProjectModal: FunctionComponent<IEditProjectModalProps> = ({
	open,
	onOpenChange,
	project,
	onUpdated,
}): JSX.Element => {
	const { control, register, handleSubmit, reset, formState } =
		useForm<IEditProjectFormData>({
			defaultValues: {
				name: project.name,
				description: project.description ?? "",
				language: project.language,
			},
		})

	const { mutate, isPending } = useUpdateProject({
		onSuccess: async () => {
			await onUpdated?.()
			onOpenChange?.(false)
		},
		onError: (error) => {
			console.error("Update project failed:", error)
		},
	})

	useEffect(() => {
		if (open) {
			reset({
				name: project.name,
				description: project.description ?? "",
				language: project.language,
			})
		}
	}, [open, project, reset])

	const onSubmit = (data: IEditProjectFormData): void => {
		const name = data.name.trim()
		const description = data.description?.trim()

		mutate({
			params: { path: { project_id: project.id } },
			body: {
				name,
				description: description?.length ? description : null,
				language: data.language,
			},
		})
	}

	return (
		<Modal
			open={open}
			onOpenChange={onOpenChange}
			title="Изменить проект"
			description="Измените параметры проекта"
		>
			<div className={styles.root} data-testid="EditProjectModal">
				<Form onSubmit={handleSubmit(onSubmit)}>
					<div className={styles.fields}>
						<TextField
							id="project_name"
							label="Название"
							placeholder="Например: Мой первый проект"
							error={Boolean(formState.errors.name)}
							undertitle={formState.errors.name?.message}
							{...register("name", {
								required: "Введите название проекта",
								validate: (v) =>
									v.trim().length > 0 || "Введите название проекта",
							})}
						/>

						<TextField
							id="project_description"
							label="Описание"
							placeholder="Коротко опишите проект (необязательно)"
							{...register("description")}
						/>

						<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>
					</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>
	)
}
