"use client"

import type { JSX } from "react"

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

import { useHookFormMask } from "use-mask-input"

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

import { IRegisterPageProps } from "./RegisterPage.d"
import styles from "./RegisterPage.module.scss"

interface IRegisterFormData {
	username: string
	email: string
	password: string
	first_name: string
	last_name: string
	phone_number?: string
	avatar?: string
}

export const RegisterPage: FunctionComponent<
	IRegisterPageProps
> = (): JSX.Element => {
	const { mutate, isPending } = api.useMutation("post", "/auth/register", {
		onSuccess: (data) => {
			console.log("Register successful:", data)
		},
		onError: (error) => {
			console.error("Register failed:", error)
		},
	})

	const { register, handleSubmit } = useForm<IRegisterFormData>()
	const registerWithMask = useHookFormMask(register)

	const onSubmit = (data: IRegisterFormData): void => {
		const phone = data.phone_number?.trim()
		const avatar = data.avatar?.trim()

		mutate({
			body: {
				username: data.username,
				email: data.email,
				password: data.password,
				first_name: data.first_name,
				last_name: data.last_name,
				phone_number: phone || undefined,
				avatar: avatar || undefined,
			},
		})
	}

	return (
		<div className={styles.root} data-testid="RegisterPage">
			<Form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
				<h1 className={styles.title}>Регистрация</h1>
				<div className={styles.fields}>
					<TextField
						id="username"
						label="Имя пользователя"
						placeholder="Ваш никнейм"
						{...register("username")}
					/>
					<TextField
						id="email"
						label="Email"
						placeholder="you@example.com"
						type="email"
						{...register("email")}
					/>
					<TextField
						id="password"
						label="Пароль"
						placeholder="Придумайте пароль"
						type="password"
						{...register("password")}
					/>
					<TextField
						id="first_name"
						label="Имя"
						placeholder="Ваше имя"
						{...register("first_name")}
					/>
					<TextField
						id="last_name"
						label="Фамилия"
						placeholder="Ваша фамилия"
						{...register("last_name")}
					/>
					<TextField
						id="phone_number"
						label="Номер телефона"
						placeholder="+7 (___) ___-__-__"
						{...registerWithMask("phone_number", "+7 (999) 999-99-99")}
					/>
					<TextField
						id="avatar"
						label="Аватар"
						placeholder="Ссылка на изображение"
						{...register("avatar")}
					/>
				</div>
				<Button type="submit" variant="primary" disabled={isPending}>
					Создать аккаунт
				</Button>
			</Form>
		</div>
	)
}
