import React, {Dispatch, SetStateAction, useContext, useState} from "react";
import System from "@/lib/models/System";
import {AlertContext} from "@/context/AlertContext";
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faEnvelope, faLock, faSignature, faUser} from '@fortawesome/free-solid-svg-icons';
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";

export default function StepOne(
    {
        username,
        email,
        setUsername,
        setEmail,
        handleNextStep
    }: {
        username: string;
        email: string;
        setUsername: Dispatch<SetStateAction<string>>,
        setEmail: Dispatch<SetStateAction<string>>,
        handleNextStep: Function;
    }) {
    const {errorMessage, successMessage} = useContext(AlertContext);
    const [firstName, setFirstName] = useState<string>('');
    const [lastName, setLastName] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [repeatPassword, setRepeatPassword] = useState<string>('');
    const [userId, setUserId] = useState<string>('')
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)
    
    async function handleStep(): Promise<void> {
        
        if (!firstName || !lastName || !username || !password || !repeatPassword || !email) {
            errorMessage(t('registerStepOne.error.requiredFields'));
            return;
        }
        if (firstName.length < 2 || firstName.length > 50) {
            errorMessage(t('registerStepOne.error.firstNameLength'));
            return;
        }
        if (lastName.length < 2 || lastName.length > 50) {
            errorMessage(t('registerStepOne.error.lastNameLength'));
            return;
        }
        if (username.length < 3 || username.length > 50) {
            errorMessage(t('registerStepOne.error.usernameLength'));
            return;
        }
        if (System.verifyInput(firstName) || System.verifyInput(lastName) || System.verifyInput(username) || System.verifyInput(password) || System.verifyInput(repeatPassword) || System.verifyInput(email)) {
            errorMessage(t('registerStepOne.error.invalidInput'));
            return;
        }
        
        if (password != repeatPassword) {
            errorMessage(t('registerStepOne.error.passwordMismatch'));
            return;
        }
        try {
            const response: string = await System.postToServer<string>(`register/pre`, {
                firstName,
                lastName,
                username,
                email,
                password,
                retypePass: repeatPassword
            }, lang);
            if (!response) {
                errorMessage(t('registerStepOne.error.preRegister'));
                return;
            }
            setUserId(response);
            successMessage(t('registerStepOne.success.preRegister'));
            handleNextStep();
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('registerStepOne.error.unknown'));
            }
        }
    }
    
    return (
        <form className="space-y-4">
            <div className="mb-4">
                <label htmlFor="firstName" className="block text-sm font-medium mb-1 text-muted">
                    {t('registerStepOne.fields.firstName.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faSignature}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="text"
                        id="firstName"
                        placeholder={t('registerStepOne.fields.firstName.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                        required
                    />
                </div>
            </div>
            <div className="mb-4">
                <label htmlFor="lastName" className="block text-sm font-medium mb-1 text-muted">
                    {t('registerStepOne.fields.lastName.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faSignature}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="text"
                        id="lastName"
                        placeholder={t('registerStepOne.fields.lastName.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={lastName}
                        onChange={(e) => setLastName(e.target.value)}
                        required
                    />
                </div>
            </div>
            <div className="mb-4">
                <label htmlFor="username" className="block text-sm font-medium mb-1 text-muted">
                    {t('registerStepOne.fields.username.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faUser}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="text"
                        id="username"
                        placeholder={t('registerStepOne.fields.username.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        required
                    />
                </div>
                <p className="text-xs text-muted mt-1">{t('registerStepOne.fields.username.note')}</p>
            </div>
            <div className="mb-4">
                <label htmlFor="email" className="block text-sm font-medium mb-1 text-muted">
                    {t('registerStepOne.fields.email.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faEnvelope}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="email"
                        id="email"
                        placeholder={t('registerStepOne.fields.email.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        required
                    />
                </div>
            </div>
            
            <div className="mb-4">
                <label htmlFor="password" className="block text-sm font-medium mb-1 text-muted">
                    {t('registerStepOne.fields.password.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faLock}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="password"
                        id="password"
                        placeholder={t('registerStepOne.fields.password.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                </div>
            </div>
            <div className="mb-4">
                <label htmlFor="repeatPassword" className="block text-sm font-medium mb-1 text-muted">
                    {t('registerStepOne.fields.repeatPassword.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faLock}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="password"
                        id="repeatPassword"
                        placeholder={t('registerStepOne.fields.repeatPassword.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={repeatPassword}
                        onChange={(e) => setRepeatPassword(e.target.value)}
                        required
                    />
                </div>
            </div>
            <button
                type="button"
                onClick={() => handleStep()}
                className="w-full py-4 mt-6 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all"
            >
                {t('registerStepOne.next')}
            </button>
        </form>
    )
}
