/**
 * Profile Page Component
 *
 * @package Advanced_Customer_Account
 */

import { useEffect, useState, useCallback } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';

// Components
import { Card, LoadingSpinner, Notice } from '../components/Common';

/**
 * Profile page component.
 *
 * @param {Object}   props          Component props.
 * @param {Function} props.navigate Navigate function.
 * @return {JSX.Element} Profile page.
 */
const Profile = ( { navigate } ) => {
    const { fetchProfile, updateProfile, updatePassword, clearMessages } = useDispatch( 'aca/profile' );

    const { profile, isLoading, isSaving, error, successMessage } = useSelect(
        ( select ) => {
            const profileStore = select( 'aca/profile' );
            return {
                profile: profileStore.getProfile(),
                isLoading: profileStore.isLoading(),
                isSaving: profileStore.isSaving(),
                error: profileStore.getError(),
                successMessage: profileStore.getSuccessMessage(),
            };
        },
        []
    );

    // Form states
    const [ profileForm, setProfileForm ] = useState( {
        first_name: '',
        last_name: '',
        display_name: '',
        email: '',
    } );

    const [ passwordForm, setPasswordForm ] = useState( {
        current_password: '',
        new_password: '',
        confirm_password: '',
    } );

    const [ formErrors, setFormErrors ] = useState( {} );
    const [ activeTab, setActiveTab ] = useState( 'profile' );

    // Fetch profile on mount
    useEffect( () => {
        fetchProfile();

        return () => {
            clearMessages();
        };
    }, [ fetchProfile, clearMessages ] );

    // Initialize form with profile data
    useEffect( () => {
        if ( profile ) {
            setProfileForm( {
                first_name: profile.first_name || '',
                last_name: profile.last_name || '',
                display_name: profile.display_name || '',
                email: profile.email || '',
            } );
        }
    }, [ profile ] );

    // Handle profile form change
    const handleProfileChange = ( field ) => ( event ) => {
        setProfileForm( ( prev ) => ( {
            ...prev,
            [ field ]: event.target.value,
        } ) );
        setFormErrors( ( prev ) => ( { ...prev, [ field ]: null } ) );
    };

    // Handle password form change
    const handlePasswordChange = ( field ) => ( event ) => {
        setPasswordForm( ( prev ) => ( {
            ...prev,
            [ field ]: event.target.value,
        } ) );
        setFormErrors( ( prev ) => ( { ...prev, [ field ]: null } ) );
    };

    // Validate profile form
    const validateProfileForm = () => {
        const errors = {};

        if ( ! profileForm.first_name.trim() ) {
            errors.first_name = __( 'First name is required.', 'advanced-customer-account' );
        }
        if ( ! profileForm.last_name.trim() ) {
            errors.last_name = __( 'Last name is required.', 'advanced-customer-account' );
        }
        if ( ! profileForm.display_name.trim() ) {
            errors.display_name = __( 'Display name is required.', 'advanced-customer-account' );
        }
        if ( ! profileForm.email.trim() ) {
            errors.email = __( 'Email is required.', 'advanced-customer-account' );
        } else {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if ( ! emailRegex.test( profileForm.email ) ) {
                errors.email = __( 'Please enter a valid email address.', 'advanced-customer-account' );
            }
        }

        return errors;
    };

    // Validate password form
    const validatePasswordForm = () => {
        const errors = {};

        if ( ! passwordForm.current_password ) {
            errors.current_password = __( 'Current password is required.', 'advanced-customer-account' );
        }
        if ( ! passwordForm.new_password ) {
            errors.new_password = __( 'New password is required.', 'advanced-customer-account' );
        } else if ( passwordForm.new_password.length < 8 ) {
            errors.new_password = __( 'Password must be at least 8 characters.', 'advanced-customer-account' );
        }
        if ( passwordForm.new_password !== passwordForm.confirm_password ) {
            errors.confirm_password = __( 'Passwords do not match.', 'advanced-customer-account' );
        }

        return errors;
    };

    // Handle profile form submit
    const handleProfileSubmit = async ( event ) => {
        event.preventDefault();
        clearMessages();

        const errors = validateProfileForm();
        if ( Object.keys( errors ).length > 0 ) {
            setFormErrors( errors );
            return;
        }

        try {
            await updateProfile( profileForm );
        } catch ( err ) {
            // Error handled by store
        }
    };

    // Handle password form submit
    const handlePasswordSubmit = async ( event ) => {
        event.preventDefault();
        clearMessages();

        const errors = validatePasswordForm();
        if ( Object.keys( errors ).length > 0 ) {
            setFormErrors( errors );
            return;
        }

        try {
            await updatePassword( passwordForm );
            // Clear password form on success
            setPasswordForm( {
                current_password: '',
                new_password: '',
                confirm_password: '',
            } );
        } catch ( err ) {
            // Error handled by store
        }
    };

    if ( isLoading && ! profile ) {
        return <LoadingSpinner fullPage message={ __( 'Loading profile...', 'advanced-customer-account' ) } />;
    }

    return (
        <div className="aca-profile-page">
            { /* Notifications */ }
            { error && (
                <Notice
                    type="error"
                    message={ error }
                    onDismiss={ () => clearMessages() }
                />
            ) }

            { successMessage && (
                <Notice
                    type="success"
                    message={ successMessage }
                    onDismiss={ () => clearMessages() }
                    autoDismiss={ 5000 }
                />
            ) }

            { /* Tab navigation */ }
            <div className="aca-profile-page__tabs">
                <button
                    type="button"
                    className={ `aca-profile-page__tab ${ activeTab === 'profile' ? 'aca-profile-page__tab--active' : '' }` }
                    onClick={ () => setActiveTab( 'profile' ) }
                >
                    { __( 'Account Details', 'advanced-customer-account' ) }
                </button>
                <button
                    type="button"
                    className={ `aca-profile-page__tab ${ activeTab === 'password' ? 'aca-profile-page__tab--active' : '' }` }
                    onClick={ () => setActiveTab( 'password' ) }
                >
                    { __( 'Change Password', 'advanced-customer-account' ) }
                </button>
            </div>

            { /* Profile form */ }
            { activeTab === 'profile' && (
                <Card className="aca-profile-page__card">
                    <form onSubmit={ handleProfileSubmit } className="aca-profile-form">
                        <div className="aca-profile-form__row">
                            <div className="aca-form-field">
                                <label htmlFor="first_name" className="aca-form-field__label">
                                    { __( 'First name', 'advanced-customer-account' ) }
                                    <span className="required">*</span>
                                </label>
                                <input
                                    type="text"
                                    id="first_name"
                                    className={ `aca-form-field__input ${ formErrors.first_name ? 'aca-form-field__input--error' : '' }` }
                                    value={ profileForm.first_name }
                                    onChange={ handleProfileChange( 'first_name' ) }
                                />
                                { formErrors.first_name && (
                                    <span className="aca-form-field__error">{ formErrors.first_name }</span>
                                ) }
                            </div>

                            <div className="aca-form-field">
                                <label htmlFor="last_name" className="aca-form-field__label">
                                    { __( 'Last name', 'advanced-customer-account' ) }
                                    <span className="required">*</span>
                                </label>
                                <input
                                    type="text"
                                    id="last_name"
                                    className={ `aca-form-field__input ${ formErrors.last_name ? 'aca-form-field__input--error' : '' }` }
                                    value={ profileForm.last_name }
                                    onChange={ handleProfileChange( 'last_name' ) }
                                />
                                { formErrors.last_name && (
                                    <span className="aca-form-field__error">{ formErrors.last_name }</span>
                                ) }
                            </div>
                        </div>

                        <div className="aca-form-field">
                            <label htmlFor="display_name" className="aca-form-field__label">
                                { __( 'Display name', 'advanced-customer-account' ) }
                                <span className="required">*</span>
                            </label>
                            <input
                                type="text"
                                id="display_name"
                                className={ `aca-form-field__input ${ formErrors.display_name ? 'aca-form-field__input--error' : '' }` }
                                value={ profileForm.display_name }
                                onChange={ handleProfileChange( 'display_name' ) }
                            />
                            <span className="aca-form-field__help">
                                { __( 'This will be how your name will be displayed in the account section and in reviews.', 'advanced-customer-account' ) }
                            </span>
                            { formErrors.display_name && (
                                <span className="aca-form-field__error">{ formErrors.display_name }</span>
                            ) }
                        </div>

                        <div className="aca-form-field">
                            <label htmlFor="email" className="aca-form-field__label">
                                { __( 'Email address', 'advanced-customer-account' ) }
                                <span className="required">*</span>
                            </label>
                            <input
                                type="email"
                                id="email"
                                className={ `aca-form-field__input ${ formErrors.email ? 'aca-form-field__input--error' : '' }` }
                                value={ profileForm.email }
                                onChange={ handleProfileChange( 'email' ) }
                            />
                            { formErrors.email && (
                                <span className="aca-form-field__error">{ formErrors.email }</span>
                            ) }
                        </div>

                        <div className="aca-profile-form__actions">
                            <button
                                type="submit"
                                className="aca-btn aca-btn--primary"
                                disabled={ isSaving }
                            >
                                { isSaving
                                    ? __( 'Saving...', 'advanced-customer-account' )
                                    : __( 'Save Changes', 'advanced-customer-account' )
                                }
                            </button>
                        </div>
                    </form>
                </Card>
            ) }

            { /* Password form */ }
            { activeTab === 'password' && (
                <Card className="aca-profile-page__card">
                    <form onSubmit={ handlePasswordSubmit } className="aca-profile-form">
                        <div className="aca-form-field">
                            <label htmlFor="current_password" className="aca-form-field__label">
                                { __( 'Current password', 'advanced-customer-account' ) }
                                <span className="required">*</span>
                            </label>
                            <input
                                type="password"
                                id="current_password"
                                className={ `aca-form-field__input ${ formErrors.current_password ? 'aca-form-field__input--error' : '' }` }
                                value={ passwordForm.current_password }
                                onChange={ handlePasswordChange( 'current_password' ) }
                                autoComplete="current-password"
                            />
                            { formErrors.current_password && (
                                <span className="aca-form-field__error">{ formErrors.current_password }</span>
                            ) }
                        </div>

                        <div className="aca-form-field">
                            <label htmlFor="new_password" className="aca-form-field__label">
                                { __( 'New password', 'advanced-customer-account' ) }
                                <span className="required">*</span>
                            </label>
                            <input
                                type="password"
                                id="new_password"
                                className={ `aca-form-field__input ${ formErrors.new_password ? 'aca-form-field__input--error' : '' }` }
                                value={ passwordForm.new_password }
                                onChange={ handlePasswordChange( 'new_password' ) }
                                autoComplete="new-password"
                            />
                            <span className="aca-form-field__help">
                                { __( 'Password must be at least 8 characters.', 'advanced-customer-account' ) }
                            </span>
                            { formErrors.new_password && (
                                <span className="aca-form-field__error">{ formErrors.new_password }</span>
                            ) }
                        </div>

                        <div className="aca-form-field">
                            <label htmlFor="confirm_password" className="aca-form-field__label">
                                { __( 'Confirm new password', 'advanced-customer-account' ) }
                                <span className="required">*</span>
                            </label>
                            <input
                                type="password"
                                id="confirm_password"
                                className={ `aca-form-field__input ${ formErrors.confirm_password ? 'aca-form-field__input--error' : '' }` }
                                value={ passwordForm.confirm_password }
                                onChange={ handlePasswordChange( 'confirm_password' ) }
                                autoComplete="new-password"
                            />
                            { formErrors.confirm_password && (
                                <span className="aca-form-field__error">{ formErrors.confirm_password }</span>
                            ) }
                        </div>

                        <div className="aca-profile-form__actions">
                            <button
                                type="submit"
                                className="aca-btn aca-btn--primary"
                                disabled={ isSaving }
                            >
                                { isSaving
                                    ? __( 'Saving...', 'advanced-customer-account' )
                                    : __( 'Change Password', 'advanced-customer-account' )
                                }
                            </button>
                        </div>
                    </form>
                </Card>
            ) }
        </div>
    );
};

export default Profile;
