// User Contact Info Edit Component
// Displays and configures user contact information with various display options

import { __ } from '@wordpress/i18n';
import {
    InspectorControls,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    ToggleControl,
    TextControl,
    ColorPalette
} from '@wordpress/components';
import { Fragment } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import MultiSelect from '../../components/MultiSelect';

const Edit = ({ attributes, setAttributes, context }) => {
    const {
        showFields,
        layoutStyle,
        showIcons,
        iconSize,
        showLabels,
        emailLink,
        websiteLink,
        phoneLink,
        align,
        iconColor
    } = attributes;

    // Get user data from context prop (Query Loop style)
    	const user = context?.['wpuf-ud/userObject'] || {
        id: 0,
        display_name: __('Sample User', 'wpuf-pro'),
        user_login: 'sampleuser',
        user_email: 'sample@example.com',
        user_url: 'https://example.com',
        meta: {
            'wpuf_profile_phone': '+1 (555) 123-4567',
            'phone_number': '+1 (555) 123-4567',
            'location': 'New York, NY',
            'company': 'Sample Company',
            'job_title': 'Sample Job Title',
            'social_facebook': 'https://facebook.com/sampleuser',
            'social_twitter': 'https://twitter.com/sampleuser',
            'social_linkedin': 'https://linkedin.com/in/sampleuser'
        }
    };

    // Detect container context for styling
    	const containerLayout = context?.['wpuf-ud/containerLayout'] || 'default';
	const isInDirectory = context?.['wpuf-ud/isDirectoryMode'] || false;

    // Get theme colors for ColorPalette
    const colors = useSelect(select => {
        return select('core/block-editor').getSettings().colors || [];
    }, []);

    const blockProps = useBlockProps({
        className: `wpuf-contact wpuf-layout-${layoutStyle} wpuf-container-${containerLayout} ${isInDirectory ? 'wpuf-in-directory' : 'wpuf-in-profile'}${align ? ` has-text-align-${align}` : ''}`
    });

    // Get contact fields based on settings
    const getContactFields = () => {
        const fields = [];

        // Ensure showFields is an array
        const selectedFields = Array.isArray(showFields) ? showFields : [showFields];

        if (selectedFields.includes('all') || selectedFields.includes('email')) {
            fields.push({
                type: 'email',
                label: __('Email', 'wpuf-pro'),
                value: user.user_email,
                icon: '<svg width="19" height="14" viewBox="0 0 19 14" fill="none" xmlns="http://www.w3.org/2000/svg">\n' +
                    '<path d="M17.625 2.625V11.375C17.625 12.4105 16.7855 13.25 15.75 13.25H3.25C2.21447 13.25 1.375 12.4105 1.375 11.375V2.625M17.625 2.625C17.625 1.58947 16.7855 0.75 15.75 0.75H3.25C2.21447 0.75 1.375 1.58947 1.375 2.625M17.625 2.625V2.82726C17.625 3.47837 17.2872 4.08287 16.7327 4.42412L10.4827 8.27027C9.88004 8.64113 9.11996 8.64113 8.51732 8.27027L2.26732 4.42412C1.71279 4.08287 1.375 3.47837 1.375 2.82726V2.625" stroke="' + (iconColor || '#3B82F6') + '" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n' +
                    '</svg>\n'
            });
        }

        if (selectedFields.includes('all') || selectedFields.includes('website')) {
            fields.push({
                type: 'website',
                label: __('Website', 'wpuf-pro'),
                value: user.user_url,
                icon: '<svg width="17" height="18" viewBox="0 0 17 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n' +
                    '<path d="M8.5 16.5C11.9938 16.5 14.9296 14.111 15.7631 10.8775M8.5 16.5C5.00619 16.5 2.07035 14.111 1.23692 10.8775M8.5 16.5C10.5711 16.5 12.25 13.1421 12.25 9C12.25 4.85786 10.5711 1.5 8.5 1.5M8.5 16.5C6.42893 16.5 4.75 13.1421 4.75 9C4.75 4.85786 6.42893 1.5 8.5 1.5M8.5 1.5C11.3043 1.5 13.7492 3.03912 15.0359 5.31871M8.5 1.5C5.69567 1.5 3.25083 3.03912 1.9641 5.31871M15.0359 5.31871C13.2831 6.83366 10.9986 7.75 8.5 7.75C6.00143 7.75 3.71689 6.83366 1.9641 5.31871M15.0359 5.31871C15.6497 6.40619 16 7.66219 16 9C16 9.64832 15.9177 10.2774 15.7631 10.8775M15.7631 10.8775C13.6111 12.0706 11.1349 12.75 8.5 12.75C5.86509 12.75 3.38885 12.0706 1.23692 10.8775M1.23692 10.8775C1.08226 10.2774 1 9.64832 1 9C1 7.66219 1.35027 6.40619 1.9641 5.31871" stroke="' + (iconColor || '#3B82F6') + '" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n' +
                    '</svg>\n'
            });
        }

        if (selectedFields.includes('all') || selectedFields.includes('phone')) {
            const phoneValue = user?.meta?.wpuf_profile_phone || user?.wpuf_profile_phone || '';
            if (phoneValue) {
                fields.push({
                    type: 'phone',
                    label: __('Phone', 'wpuf-pro'),
                    value: phoneValue,
                    icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n' +
                        '<path d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z" stroke="' + (iconColor || '#3B82F6') + '" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>\n' +
                        '</svg>\n'
                });
            }
        }

        const filteredFields = fields.filter(field => field.value);
        return filteredFields;
    };

    const contactFields = getContactFields();

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('Contact Info Settings', 'wpuf-pro')} initialOpen={true}>
                    <div className='wpuf-mb-4'>
                        <label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700 wpuf-mb-2">
                            {__('Show Fields', 'wpuf-pro')}
                        </label>
                        <MultiSelect
                            options={{
                                all: __('All Fields', 'wpuf-pro'),
                                email: __('Email', 'wpuf-pro'),
                                website: __('Website', 'wpuf-pro'),
                                phone: __('Phone', 'wpuf-pro')
                            }}
                            value={Array.isArray(showFields) ? showFields : [showFields]}
                            onChange={(value) => setAttributes({ showFields: value })}
                            placeholder={__('Select fields to display', 'wpuf-pro')}
                            sortable={true}
                        />
                    </div>

                    <SelectControl
                        label={__('Layout Style', 'wpuf-pro')}
                        value={layoutStyle}
                        options={[
                            { label: __('List', 'wpuf-pro'), value: 'list' },
                            { label: __('Inline', 'wpuf-pro'), value: 'inline' }
                        ]}
                        onChange={(value) => setAttributes({ layoutStyle: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Show Icons', 'wpuf-pro')}
                        checked={showIcons}
                        onChange={(value) => setAttributes({ showIcons: value })}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Show Labels', 'wpuf-pro')}
                        checked={showLabels}
                        onChange={(value) => setAttributes({ showLabels: value })}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Email as Link', 'wpuf-pro')}
                        checked={emailLink}
                        onChange={(value) => setAttributes({ emailLink: value })}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Website as Link', 'wpuf-pro')}
                        checked={websiteLink}
                        onChange={(value) => setAttributes({ websiteLink: value })}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Phone as Link', 'wpuf-pro')}
                        checked={phoneLink}
                        onChange={(value) => setAttributes({ phoneLink: value })}
                        __nextHasNoMarginBottom={true}
                    />

                    <ColorPalette
                        label={__('Icon Color', 'wpuf-pro')}
                        colors={colors}
                        value={iconColor}
                        onChange={(value) => setAttributes({ iconColor: value })}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                {contactFields.length > 0 ? (
                    <div className="wpuf-contact-fields">
                        {contactFields.map((field, index) => (
                            <div key={index} className={`wpuf-contact-field wpuf-field-${field.type}`}>
                                {showIcons && (
                                    <span
                                        className={`wpuf-field-icon wpuf-icon-${iconSize}`}
                                        dangerouslySetInnerHTML={{ __html: field.icon }}
                                    />
                                )}

                                {showLabels && (
                                    <span className="wpuf-field-label">
                                        {field.label}:
                                    </span>
                                )}

                                <span className="wpuf-field-value">
                                    {field.type === 'email' && emailLink ? (
                                        <a href={`mailto:${field.value}`}>
                                            {field.value}
                                        </a>
                                    ) : field.type === 'website' && websiteLink ? (
                                        <a href={field.value} target="_blank" rel="noopener noreferrer">
                                            {field.value}
                                        </a>
                                    ) : field.type === 'phone' && phoneLink ? (
                                        <a href={`tel:${field.value}`}>
                                            {field.value}
                                        </a>
                                    ) : (
                                        field.value
                                    )}
                                </span>
                            </div>
                        ))}
                    </div>
                ) : (
                    <p className="wpuf-no-contact-info">
                        {__('No contact information available.', 'wpuf-pro')}
                    </p>
                )}
            </div>
        </Fragment>
    );
};

export default Edit;
