"use client"

import type { IChangePasswordFormProps } from "./ChangePasswordForm.d"
import type { JSX } from "react"

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

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

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

interface IPasswordFormData {
	current_password: string
	new_password: string
	confirm_password: string
}

export const ChangePasswordForm: FunctionComponent<
	IChangePasswordFormProps
> = ({ className }): JSX.Element => {
	const [successMessage, setSuccessMessage] = useState(false)
	const [errorMessage, setErrorMessage] = useState<string | null>(null)

	const { register, handleSubmit, reset, formState: { errors } } = useForm<IPasswordFormData>({
		defaultValues: {
			current_password: "",
			new_password: "",
			confirm_password: "",
		},
	})

	const { mutate, isPending } = api.useMutation(
		"post",
		"/api/users/me/change-password/",
		{
			onSuccess: () => {
				setErrorMessage(null)
				setSuccessMessage(true)
				reset()
				setTimeout(() => setSuccessMessage(false), 3000)
			},
			onError: (error) => {
				setSuccessMessage(false)
				setErrorMessage(
					(error as { detail?: string })?.detail || "Не удалось сменить пароль",
				)
			},
		},
	)

	const onSubmit = (data: IPasswordFormData) => {
		setErrorMessage(null)
		mutate({
			body: {
				current_password: data.current_password,
				new_password: data.new_password,
			},
		})
	}

	return (
		<div className={className} data-testid="ChangePasswordForm">
			<h3 className={styles.title}>Смена пароля</h3>
			<Form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
				<div className={styles.fields}>
					<TextField
						id="current_password"
						label="Текущий пароль"
						placeholder="Введите текущий пароль"
						type="password"
						{...register("current_password", { required: "Обязательное поле" })}
					/>
					<TextField
						id="new_password"
						label="Новый пароль"
						placeholder="Введите новый пароль"
						type="password"
						{...register("new_password", { required: "Обязательное поле" })}
					/>
					<TextField
						id="confirm_password"
						label="Подтверждение пароля"
						placeholder="Повторите новый пароль"
						type="password"
						error={!!errors.confirm_password}
						{...register("confirm_password", {
							required: "Обязательное поле",
							validate: (value, formValues) =>
								value === formValues.new_password || "Пароли не совпадают",
						})}
					/>
					{errors.confirm_password && (
						<Alert variant="danger">{errors.confirm_password.message}</Alert>
					)}
				</div>
				{successMessage && (
					<Alert variant="success">Пароль успешно изменён</Alert>
				)}
				{errorMessage && <Alert variant="danger">{errorMessage}</Alert>}
				<Button type="submit" variant="primary" disabled={isPending}>
					{isPending ? "Сохранение..." : "Сменить пароль"}
				</Button>
			</Form>
		</div>
	)
}
