/**
 * AddressForm Component
 *
 * @package Advanced_Customer_Account
 */

import { useState, useEffect, useMemo } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';

// Components
import { Notice } from '../Common';

/**
 * Address form component.
 *
 * @param {Object}   props           Component props.
 * @param {string}   props.type      Address type (billing/shipping).
 * @param {Object}   props.address   Current address data.
 * @param {Array}    props.countries Countries list.
 * @param {Function} props.onCancel  Cancel handler.
 * @param {Function} props.onSuccess Success handler.
 * @param {boolean}  props.isSaving  Saving state.
 * @return {JSX.Element} AddressForm component.
 */
const AddressForm = ( { type, address, countries, onCancel, onSuccess, isSaving } ) => {
    const { updateAddress, fetchStates, clearMessages } = useDispatch( 'aca/profile' );
    const [ formData, setFormData ] = useState( {
        first_name: '',
        last_name: '',
        company: '',
        address_1: '',
        address_2: '',
        city: '',
        state: '',
        postcode: '',
        country: '',
        ...( type === 'billing' ? { email: '', phone: '' } : {} ),
    } );
    const [ formError, setFormError ] = useState( null );

    // Get states from store
    const states = useSelect(
        ( select ) => select( 'aca/profile' ).getStates( formData.country ),
        [ formData.country ]
    );

    // Initialize form with address data
    useEffect( () => {
        if ( address ) {
            setFormData( ( prev ) => ( {
                ...prev,
                first_name: address.first_name || '',
                last_name: address.last_name || '',
                company: address.company || '',
                address_1: address.address_1 || '',
                address_2: address.address_2 || '',
                city: address.city || '',
                state: address.state || '',
                postcode: address.postcode || '',
                country: address.country || '',
                ...( type === 'billing' ? {
                    email: address.email || '',
                    phone: address.phone || '',
                } : {} ),
            } ) );
        }
    }, [ address, type ] );

    // Fetch states when country changes
    useEffect( () => {
        if ( formData.country ) {
            fetchStates( formData.country );
        }
    }, [ formData.country, fetchStates ] );

    // Handle input change
    const handleChange = ( field ) => ( event ) => {
        const value = event.target.value;

        setFormData( ( prev ) => {
            const updated = { ...prev, [ field ]: value };

            // Reset state when country changes
            if ( field === 'country' ) {
                updated.state = '';
            }

            return updated;
        } );
    };

    // Validate form
    const validateForm = () => {
        if ( ! formData.first_name.trim() ) {
            return __( 'First name is required.', 'advanced-customer-account' );
        }
        if ( ! formData.last_name.trim() ) {
            return __( 'Last name is required.', 'advanced-customer-account' );
        }
        if ( ! formData.address_1.trim() ) {
            return __( 'Street address is required.', 'advanced-customer-account' );
        }
        if ( ! formData.city.trim() ) {
            return __( 'City is required.', 'advanced-customer-account' );
        }
        if ( ! formData.country ) {
            return __( 'Country is required.', 'advanced-customer-account' );
        }

        // Billing specific validations
        if ( type === 'billing' ) {
            if ( ! formData.email?.trim() ) {
                return __( 'Email is required.', 'advanced-customer-account' );
            }
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if ( ! emailRegex.test( formData.email ) ) {
                return __( 'Please enter a valid email address.', 'advanced-customer-account' );
            }
        }

        return null;
    };

    // Handle form submit
    const handleSubmit = async ( event ) => {
        event.preventDefault();
        setFormError( null );
        clearMessages();

        const validationError = validateForm();
        if ( validationError ) {
            setFormError( validationError );
            return;
        }

        try {
            await updateAddress( type, formData );
            onSuccess();
        } catch ( err ) {
            setFormError( err.message || __( 'Failed to save address.', 'advanced-customer-account' ) );
        }
    };

    // Countries as options
    const countryOptions = useMemo( () => {
        if ( Array.isArray( countries ) ) {
            return countries;
        }
        // Convert object to array
        return Object.entries( countries || {} ).map( ( [ code, name ] ) => ( {
            code,
            name,
        } ) );
    }, [ countries ] );

    // States as options
    const stateOptions = useMemo( () => {
        if ( Array.isArray( states ) ) {
            return states;
        }
        // Convert object to array
        return Object.entries( states || {} ).map( ( [ code, name ] ) => ( {
            code,
            name,
        } ) );
    }, [ states ] );

    return (
        <form className="aca-address-form" onSubmit={ handleSubmit }>
            { formError && (
                <Notice
                    type="error"
                    message={ formError }
                    onDismiss={ () => setFormError( null ) }
                />
            ) }

            <div className="aca-address-form__row">
                <div className="aca-form-field">
                    <label htmlFor={ `${ type }_first_name` } className="aca-form-field__label">
                        { __( 'First name', 'advanced-customer-account' ) }
                        <span className="required">*</span>
                    </label>
                    <input
                        type="text"
                        id={ `${ type }_first_name` }
                        className="aca-form-field__input"
                        value={ formData.first_name }
                        onChange={ handleChange( 'first_name' ) }
                        required
                    />
                </div>

                <div className="aca-form-field">
                    <label htmlFor={ `${ type }_last_name` } className="aca-form-field__label">
                        { __( 'Last name', 'advanced-customer-account' ) }
                        <span className="required">*</span>
                    </label>
                    <input
                        type="text"
                        id={ `${ type }_last_name` }
                        className="aca-form-field__input"
                        value={ formData.last_name }
                        onChange={ handleChange( 'last_name' ) }
                        required
                    />
                </div>
            </div>

            <div className="aca-form-field">
                <label htmlFor={ `${ type }_company` } className="aca-form-field__label">
                    { __( 'Company', 'advanced-customer-account' ) }
                </label>
                <input
                    type="text"
                    id={ `${ type }_company` }
                    className="aca-form-field__input"
                    value={ formData.company }
                    onChange={ handleChange( 'company' ) }
                />
            </div>

            <div className="aca-form-field">
                <label htmlFor={ `${ type }_country` } className="aca-form-field__label">
                    { __( 'Country / Region', 'advanced-customer-account' ) }
                    <span className="required">*</span>
                </label>
                <select
                    id={ `${ type }_country` }
                    className="aca-form-field__select"
                    value={ formData.country }
                    onChange={ handleChange( 'country' ) }
                    required
                >
                    <option value="">{ __( 'Select a country...', 'advanced-customer-account' ) }</option>
                    { countryOptions.map( ( country ) => (
                        <option key={ country.code } value={ country.code }>
                            { country.name }
                        </option>
                    ) ) }
                </select>
            </div>

            <div className="aca-form-field">
                <label htmlFor={ `${ type }_address_1` } className="aca-form-field__label">
                    { __( 'Street address', 'advanced-customer-account' ) }
                    <span className="required">*</span>
                </label>
                <input
                    type="text"
                    id={ `${ type }_address_1` }
                    className="aca-form-field__input"
                    placeholder={ __( 'House number and street name', 'advanced-customer-account' ) }
                    value={ formData.address_1 }
                    onChange={ handleChange( 'address_1' ) }
                    required
                />
                <input
                    type="text"
                    className="aca-form-field__input aca-form-field__input--mt"
                    placeholder={ __( 'Apartment, suite, unit, etc. (optional)', 'advanced-customer-account' ) }
                    value={ formData.address_2 }
                    onChange={ handleChange( 'address_2' ) }
                />
            </div>

            <div className="aca-form-field">
                <label htmlFor={ `${ type }_city` } className="aca-form-field__label">
                    { __( 'Town / City', 'advanced-customer-account' ) }
                    <span className="required">*</span>
                </label>
                <input
                    type="text"
                    id={ `${ type }_city` }
                    className="aca-form-field__input"
                    value={ formData.city }
                    onChange={ handleChange( 'city' ) }
                    required
                />
            </div>

            { stateOptions.length > 0 ? (
                <div className="aca-form-field">
                    <label htmlFor={ `${ type }_state` } className="aca-form-field__label">
                        { __( 'State / Province', 'advanced-customer-account' ) }
                    </label>
                    <select
                        id={ `${ type }_state` }
                        className="aca-form-field__select"
                        value={ formData.state }
                        onChange={ handleChange( 'state' ) }
                    >
                        <option value="">{ __( 'Select a state...', 'advanced-customer-account' ) }</option>
                        { stateOptions.map( ( state ) => (
                            <option key={ state.code } value={ state.code }>
                                { state.name }
                            </option>
                        ) ) }
                    </select>
                </div>
            ) : (
                <div className="aca-form-field">
                    <label htmlFor={ `${ type }_state` } className="aca-form-field__label">
                        { __( 'State / Province', 'advanced-customer-account' ) }
                    </label>
                    <input
                        type="text"
                        id={ `${ type }_state` }
                        className="aca-form-field__input"
                        value={ formData.state }
                        onChange={ handleChange( 'state' ) }
                    />
                </div>
            ) }

            <div className="aca-form-field">
                <label htmlFor={ `${ type }_postcode` } className="aca-form-field__label">
                    { __( 'ZIP / Postal code', 'advanced-customer-account' ) }
                </label>
                <input
                    type="text"
                    id={ `${ type }_postcode` }
                    className="aca-form-field__input"
                    value={ formData.postcode }
                    onChange={ handleChange( 'postcode' ) }
                />
            </div>

            { type === 'billing' && (
                <>
                    <div className="aca-form-field">
                        <label htmlFor={ `${ type }_email` } className="aca-form-field__label">
                            { __( 'Email address', 'advanced-customer-account' ) }
                            <span className="required">*</span>
                        </label>
                        <input
                            type="email"
                            id={ `${ type }_email` }
                            className="aca-form-field__input"
                            value={ formData.email }
                            onChange={ handleChange( 'email' ) }
                            required
                        />
                    </div>

                    <div className="aca-form-field">
                        <label htmlFor={ `${ type }_phone` } className="aca-form-field__label">
                            { __( 'Phone', 'advanced-customer-account' ) }
                        </label>
                        <input
                            type="tel"
                            id={ `${ type }_phone` }
                            className="aca-form-field__input"
                            value={ formData.phone }
                            onChange={ handleChange( 'phone' ) }
                        />
                    </div>
                </>
            ) }

            <div className="aca-address-form__actions">
                <button
                    type="submit"
                    className="aca-btn aca-btn--primary"
                    disabled={ isSaving }
                >
                    { isSaving
                        ? __( 'Saving...', 'advanced-customer-account' )
                        : __( 'Save Address', 'advanced-customer-account' )
                    }
                </button>
                <button
                    type="button"
                    className="aca-btn aca-btn--secondary"
                    onClick={ onCancel }
                    disabled={ isSaving }
                >
                    { __( 'Cancel', 'advanced-customer-account' ) }
                </button>
            </div>
        </form>
    );
};

export default AddressForm;
