import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Modal, Button, ToggleControl, SelectControl, Spinner, Snackbar } from '@wordpress/components';

const HeaderOptionsModal = ({ item, onRequestClose }) => {
    const [sticky, setSticky] = useState(false);
    const [scrollingEffect, setScrollingEffect] = useState('');
    const [animation, setAnimation] = useState('');
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [notice, setNotice] = useState(null);

    useEffect(() => {
        // Fetch existing options
        setLoading(true);
        const formData = new FormData();
        formData.append('action', 'shopbuild_get_header_options');
        formData.append('id', item.id);
        formData.append('security', window.storebuild ? window.storebuild.hf_nonce : '');

        fetch(window.ajaxurl, {
             method: 'POST',
             body: formData
        })
        .then(res => res.json())
        .then(response => {
             if(response.success && response.data) {
                 setSticky(response.data.sticky === 'yes');
                 setScrollingEffect(response.data.scrolling_effect || '');
                 setAnimation(response.data.animation || '');
             }
             setLoading(false);
        })
        .catch(() => setLoading(false));
    }, [item.id]);

    const handleSave = () => {
        setSaving(true);
        const formData = new FormData();
        formData.append('action', 'shopbuild_save_header_options');
        formData.append('id', item.id);
        formData.append('sticky', sticky ? 'yes' : 'no');
        formData.append('scrolling_effect', scrollingEffect);
        formData.append('animation', animation);
        formData.append('security', window.storebuild ? window.storebuild.hf_nonce : '');

        fetch(window.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(response => {
            setSaving(false);
            if(response.success) {
                setNotice({
                    type: 'success',
                    content: __('Options saved successfully!', 'shopbuild')
                });
                // Optional: Close after delay? No, user might want to edit more.
            } else {
                 setNotice({
                    type: 'error',
                    content: response.data || __('Error saving options', 'shopbuild')
                });
            }
        })
        .catch(() => {
             setSaving(false);
             setNotice({
                type: 'error',
                content: __('Error saving options', 'shopbuild')
            });
        });
    };

    return (
        <>
            <Modal
                title={`${__('Header Options', 'shopbuild')} - ${item.title}`}
                onRequestClose={onRequestClose}
                className="storebuild-hf-modal"
            >
                {notice && (
                    <div className="storebuild-snackbar-wrapper">
                        <Snackbar
                            onRemove={() => setNotice(null)}
                            className={notice.type === 'error' ? 'components-snackbar-error' : ''}
                        >
                            {notice.content}
                        </Snackbar>
                    </div>
                )}
                 {loading ? <div style={{padding: '20px', textAlign: 'center'}}><Spinner /></div> : (
                     <div className="storebuild-hf-options-form">
                         <ToggleControl
                             label={__('Sticky Header', 'shopbuild')}
                             checked={sticky}
                             onChange={setSticky}
                             help={sticky ? __('Header will stick to the top on scroll.', 'shopbuild') : __('Header will scroll normally.', 'shopbuild')}
                         />
    
                         <SelectControl
                             label={__('Scrolling Effect', 'shopbuild')}
                             value={scrollingEffect}
                             options={[
                                 { label: __('None', 'shopbuild'), value: '' },
                                 { label: __('Parallax', 'shopbuild'), value: 'parallax' },
                                 { label: __('Blur', 'shopbuild'), value: 'blur' },
                                 { label: __('Scale Down', 'shopbuild'), value: 'scale_down' },
                             ]}
                             onChange={setScrollingEffect}
                         />
    
                         <SelectControl
                             label={__('Entrance Animation', 'shopbuild')}
                             value={animation}
                             options={[
                                 { label: __('None', 'shopbuild'), value: '' },
                                 { label: __('Fade In', 'shopbuild'), value: 'fadeIn' },
                                 { label: __('Slide In Down', 'shopbuild'), value: 'slideInDown' },
                                 { label: __('Slide In Up', 'shopbuild'), value: 'slideInUp' },
                                 { label: __('Zoom In', 'shopbuild'), value: 'zoomIn' },
                             ]}
                             onChange={setAnimation}
                         />
    
                         <div className="storebuild-modal-footer" style={{marginTop: '20px', display: 'flex', justifyContent: 'flex-end', gap: '10px'}}>
                             <Button isTertiary onClick={onRequestClose}>
                                 {__('Cancel', 'shopbuild')}
                             </Button>
                             <Button isPrimary onClick={handleSave} isBusy={saving} disabled={saving}>
                                 {__('Save Options', 'shopbuild')}
                             </Button>
                         </div>
                     </div>
                 )}
            </Modal>
        </>
    );
};

export default HeaderOptionsModal;
