"use client"

import type { IRenameProjectModalProps } from "./RenameProjectModal.d"
import type { JSX } from "react"

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

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

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

interface IRenameProjectFormData {
	name: string
}

export const RenameProjectModal: FunctionComponent<
	IRenameProjectModalProps
> = ({ open, onOpenChange, project, onRenamed }): JSX.Element => {
	const { register, handleSubmit, reset, formState } =
		useForm<IRenameProjectFormData>({
			defaultValues: {
				name: project.name,
			},
		})

	const { mutate, isPending } = api.useMutation(
		"patch",
		"/api/projects/{project_id}/",
		{
			onSuccess: async () => {
				await onRenamed?.()
				onOpenChange?.(false)
			},
			onError: (error) => {
				console.error("Rename project failed:", error)
			},
		},
	)

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

	const onSubmit = (data: IRenameProjectFormData): void => {
		const name = data.name.trim()

		mutate({
			params: { path: { project_id: project.id } },
			body: { name },
		})
	}

	return (
		<Modal
			open={open}
			onOpenChange={onOpenChange}
			title="Переименовать проект"
			description="Введите новое название проекта"
		>
			<div className={styles.root} data-testid="RenameProjectModal">
				<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 || "Введите название проекта",
							})}
						/>
					</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>
	)
}
