"use client"

import type { IEditProfileFormProps } from "./EditProfileForm.d"
import type { JSX } from "react"

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

import api from "@shared/api"
import { useAppDispatch } from "@shared/hooks/useAppDispatch"
import { setUser } from "@shared/store/user"
import { Alert, Button, Form, TextField } from "@shared/ui"

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

interface IProfileFormData {
	first_name: string
	last_name: string
	email: string
	phone_number: string
}

export const EditProfileForm: FunctionComponent<IEditProfileFormProps> = ({
	user,
	className,
}): JSX.Element => {
	const dispatch = useAppDispatch()
	const [successMessage, setSuccessMessage] = useState(false)

	const { register, handleSubmit } = useForm<IProfileFormData>({
		defaultValues: {
			first_name: user.first_name || "",
			last_name: user.last_name || "",
			email: user.email || "",
			phone_number: user.phone_number || "",
		},
	})

	const { mutate, isPending } = api.useMutation(
		"patch",
		"/api/users/{user_id}/",
		{
			onSuccess: (data) => {
				dispatch(setUser(data))
				setSuccessMessage(true)
				setTimeout(() => setSuccessMessage(false), 3000)
			},
		},
	)

	const onSubmit = (data: IProfileFormData) => {
		mutate({
			params: { path: { user_id: user.id } },
			body: {
				first_name: data.first_name || null,
				last_name: data.last_name || null,
				email: data.email || null,
				phone_number: data.phone_number || null,
			},
		})
	}

	return (
		<div className={className} data-testid="EditProfileForm">
			<h3 className={styles.title}>Личная информация</h3>
			<Form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
				<div className={styles.fields}>
					<TextField
						id="first_name"
						label="Имя"
						placeholder="Ваше имя"
						{...register("first_name")}
					/>
					<TextField
						id="last_name"
						label="Фамилия"
						placeholder="Ваша фамилия"
						{...register("last_name")}
					/>
					<TextField
						id="email"
						label="Эл. почта"
						placeholder="Ваш email"
						type="email"
						{...register("email")}
					/>
					<TextField
						id="phone_number"
						label="Телефон"
						placeholder="Ваш телефон"
						{...register("phone_number")}
					/>
				</div>
				{successMessage && (
					<Alert variant="success">Данные успешно сохранены</Alert>
				)}
				<Button type="submit" variant="primary" disabled={isPending}>
					{isPending ? "Сохранение..." : "Сохранить"}
				</Button>
			</Form>
		</div>
	)
}
