"use client"

import type { ICreateProjectModalProps } from "./CreateProjectModal.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 { useCreateProject } from "./useCreateProject"
import styles from "./CreateProjectModal.module.scss"

interface ICreateProjectFormData {
	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 CreateProjectModal: FunctionComponent<
	ICreateProjectModalProps
> = ({ open, onOpenChange, onCreated }): JSX.Element => {
	const { control, register, handleSubmit, reset, formState } =
		useForm<ICreateProjectFormData>({
			defaultValues: {
				name: "",
				description: "",
				language: "auto",
			},
		})

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

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

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

		mutate({
			body: {
				name,
				description: description?.length ? description : undefined,
				language: data.language,
			},
		})
	}

	return (
		<Modal
			open={open}
			onOpenChange={onOpenChange}
			title="Создать проект"
			description="Заполните основные поля проекта"
		>
			<div className={styles.root} data-testid="CreateProjectModal">
				<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>
	)
}
