'use client'

import styles from '@/app/styles/module/login.module.scss';
import { ChangeEvent, useActionState, useEffect, useRef, useState } from 'react';
import { registration, FormState } from '@/app/actions/auth';
import PhoneInput from '@/app/ui/inputs/phone-input';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { IconEye } from '@/app/ui/icons/icons';
import { SignupFormSchema } from '@/app/actions/definitions';
import * as z from 'zod'

export default function RegisterForm() {
	const [state, formAction, isPending] = useActionState(
		registration,
		undefined,
	);

	const t = useTranslations('Login-register-form');
	const [showPassword, setShowPassword] = useState(false);
	const [showConfirmPassword, setShowConfirmPassword] = useState(false);
	const [formState, setFormState] = useState<FormState | undefined>(undefined);
	const passwordRef = useRef<HTMLInputElement>(null);

	useEffect(() => {
		setFormState(state);
	}, [state])

	function showPassowrd(target: 'password' | 'confirm-password') {
		if (target === 'password') {
			setShowPassword(!showPassword);
		} else {
			setShowConfirmPassword(!showConfirmPassword);
		}
	}

	function validateField(
		fieldName: string,
		value: string,
	) {
		switch (fieldName) {
			case 'confirm_password':
				const baseSchema = SignupFormSchema.shape.confirm_password;
				const baseResult = baseSchema.safeParse(value);

				if (!baseResult.success) {
					return baseResult;
				}

				const currentPassword = passwordRef.current?.value || '';
				if (value !== currentPassword) {
					return {
						success: false,
						error: new z.ZodError([
							{
								code: z.ZodIssueCode.custom,
								message: 'repeat-password',
								path: ['confirm_password']
							}
						])
					};
				}

				return { success: true, data: value };

			case 'email':
			case 'fullName':
			case 'phone':
			case 'password':
			case 'companyName':
			case 'agree':
				const schema = SignupFormSchema.shape[fieldName];
				if (fieldName === 'phone') {
					return schema.safeParse(value.replace(/[-\(\)\s]/g, ''));
				}
				return schema.safeParse(value);

			default:
				throw new Error(`Unknown field: ${fieldName}`);
		}
	}

	function onChangeHandler(e: ChangeEvent<HTMLInputElement>): void {
		const fieldName = e.target.name;
		if (fieldName !== 'phone') {
			e.target.value = e.target.value.replace(/([^a-zA-Zа-яёА-ЯЁ0-9@.!#$%&'*+/=?^_{|}~\-\s])/g, '');
		}
		const validatedField = validateField(fieldName, e.target.value);

		if (validatedField.success) {
			setFormState(prevState => {
				if (!prevState?.error || !prevState?.error[fieldName]) {
					return prevState;
				}

				const { [fieldName]: _, ...newError } = prevState.error;

				return {
					...prevState,
					error: newError
				};
			});
		}
	}

	return (
		<form action={(e) => {
			formAction(e);
		}}>
			<div className={`${styles['form-group']}`}>
				<label
					className={`${styles['form-label']} ${styles['required']}`}
				>
					{t('full-name')}
				</label>
				<input
					type="text"
					id="fullName"
					name="fullName"
					className={`${styles['form-input']}`}
					placeholder={t('name-placeholder')}
					defaultValue={formState?.previousState?.fullName ? formState?.previousState?.fullName : ''}
					onChange={onChangeHandler}
				/>
				{formState?.error?.fullName && (
					<p className="text-sm text-red-500">
						{
							formState?.error?.fullName.split('&').map((e, index) => {
								return (
									<span key={index}>
										{t(e)}
										<br />
									</span>
								)
							})
						}
					</p>
				)}
			</div>

			<div className={`${styles['form-group']}`}>
				<label className={`${styles['form-label']} ${styles['required']}`}>
					{t('email-adress')}
				</label>
				<input
					type="text"
					id="email"
					name="email"
					className={`${styles['form-input']}`}
					placeholder="ivan@example.com"
					defaultValue={formState?.previousState?.email ? formState?.previousState?.email : ''}
					onChange={(e) => {
						e.target.value = e.target.value.toLocaleLowerCase();
						onChangeHandler(e)
					}}
				/>
				{formState?.error?.email && (
					<p className="text-sm text-red-500">
						{
							formState?.error?.email.split('&').map((e, index) => {
								return (
									<span key={index}>
										{t(e)}
										<br />
									</span>
								)
							})
						}
					</p>
				)}
			</div>
			<div className={`${styles['form-group']}`}>
				<label className={`${styles['form-label']} ${styles['required']}`}>
					{t('phone')}
				</label>
				<PhoneInput phoneState={formState?.previousState?.phone} validateHandler={onChangeHandler} />
				{formState?.error?.phone && (
					<p className="text-sm text-red-500">
						{
							formState?.error?.phone.split('&').map((e, index) => {
								return (
									<span key={index}>
										{t(e)}
										<br />
									</span>
								)
							})
						}
					</p>
				)}
			</div>

			<div className={`${styles['form-group']}`}>
				<label
					className={`${styles['form-label']}`}
				>
					{t('company')}
				</label>
				<input
					type="text"
					id="companyName"
					name="companyName"
					className={`${styles['form-input']}`}
					placeholder={t('company-placeholder')}
					defaultValue={formState?.previousState?.companyName ? formState?.previousState?.companyName : ''}
					onChange={onChangeHandler}
				/>
				{formState?.error?.companyName && (
					<p className="text-sm text-red-500">
						{
							formState?.error?.companyName.split('&').map((e, index) => {
								return (
									<span key={index}>
										{t(e)}
										<br />
									</span>
								)
							})
						}
					</p>
				)}
			</div>

			<div className={`${styles['form-group']}`}>
				<label className={`${styles['form-label']} ${styles['required']}`}>
					{t('password')}
				</label>
				<div
					className={`${styles['password-wrapper']}`}
				>
					<input
						ref={passwordRef}
						type={showPassword ? "text" : "password"}
						id="password"
						name="password"
						className={`${styles['form-input']} ${styles['password']}`}
						placeholder={t('password-placeholder')}
						defaultValue={formState?.previousState?.password ? formState?.previousState?.password : ''}
						onChange={onChangeHandler}
					/>
					<button
						onClick={() => {
							showPassowrd('password')
						}}
						type="button"
						className={`show-password-button ${showPassword ? 'show' : ''}`}
					>
						<IconEye />
					</button>
				</div>
				{formState?.error?.password && (
					<p className="text-sm text-red-500">
						{
							formState?.error?.password.split('&').map((e, index) => {
								return (
									<span key={index}>
										{t(e)}
										<br />
									</span>
								)
							})
						}
					</p>
				)}
			</div>
			<div className={`${styles['form-group']}`}>
				<label className={`${styles['form-label']} ${styles['required']}`}>
					{t('confirm-password')}
				</label>
				<div className={`${styles['password-wrapper']}`}>
					<input
						type={showConfirmPassword ? "text" : "password"}
						id="confirm_password"
						name="confirm_password"
						className={`${styles['form-input']} ${styles['password']}`}
						placeholder={t('repeat-password')}
						defaultValue={formState?.previousState?.confirm_password ? formState?.previousState?.confirm_password : ''}
						onChange={onChangeHandler}
					/>
					<button
						onClick={() => {
							showPassowrd('confirm-password');
						}}
						type="button"
						className={`show-password-button ${showConfirmPassword ? 'show' : ''}`}
					>
						<IconEye />
					</button>
				</div>
				{formState?.error?.confirm_password && (
					<p className="text-sm text-red-500">
						{t(formState?.error?.confirm_password)}
					</p>
				)}
			</div>

			<div className={`${styles['form-checkbox']}`}>
				<input
					type="checkbox"
					id="agree"
					name="agree"
					defaultChecked={formState?.previousState?.agree ? true : false}
					onChange={onChangeHandler}
				/>
				<label htmlFor="agree">
					{t('i-agree-to')} <Link
						href="/terms-of-use"
						target="_blank"
					>
						{t('terms-of-use')}
					</Link> {t('and')} <Link
						href="/privacy-policy"
						target="_blank"
					>
						{t('privacy-policy')}
					</Link>
				</label>
			</div>
			{formState?.error?.agree && (
				<p className="text-sm text-red-500">
					{t(formState?.error?.agree)}
				</p>
			)}
			{formState?.error?.server && (
				<p className="text-sm text-red-500 mt-4">
					{t(formState?.error?.server)}
				</p>
			)}
			<button type="submit" className={`${styles['btn']}`}>
				{t('create-an-account')}
			</button>
		</form >
	)
}