import { select } from '@wordpress/data';
import {
    Button,
    ColorPicker,
    PanelBody,
    TextControl,
    ToggleControl,
    Flex,
    FlexBlock,
    ToolbarGroup,
    ToolbarButton
} from '@wordpress/components';
import { MediaUpload, MediaUploadCheck, MediaReplaceFlow, BlockControls } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { Image } from '@10up/block-components';

export default function BackgroundControls({ attributes, setAttributes }) {
    const {
        backgroundImage = null,
        backgroundVideo = null,
        backgroundPosition = { x: 0.5, y: 0.5 },
        backgroundOverlay = false,
        backgroundOverlayColor = null,
        placeholderDimensions = { width: '', height: '' },
    } = attributes;

    const currentUser = select('core').getCurrentUser();
    const isAdmin = currentUser?.user_role?.includes('administrator');

    const onSelectBackgroundImage = (media) => {
        setAttributes({ backgroundImage: media?.id || null });
    };

    const onRemoveBackgroundImage = () => {
        setAttributes({ backgroundImage: null });
    };

    const onSelectBackgroundVideo = (media) => {
        setAttributes({ backgroundVideo: media?.id || null });
    };

    const onRemoveBackgroundVideo = () => {
        setAttributes({ backgroundVideo: null });
    };

    return (
        <>
            <PanelBody title={__('Background', 'lead-gen')} initialOpen={false}>
                {backgroundImage && (
                    <BlockControls group="inline">
                        <ToolbarGroup>
                            <MediaReplaceFlow
                                mediaId={backgroundImage}
                                allowedTypes={['image']}
                                accept="image/*"
                                onSelect={onSelectBackgroundImage}
                            />
                            <ToolbarButton
                                onClick={onRemoveBackgroundImage}
                                icon="trash"
                                label={__('Remove Background Image', 'lead-gen')}
                            />
                        </ToolbarGroup>
                    </BlockControls>
                )}
                <Image
                    id={backgroundImage || null}
                    size="full"
                    onSelect={onSelectBackgroundImage}
                    focalPoint={backgroundPosition}
                    onChangeFocalPoint={(val) => setAttributes({ backgroundPosition: val })}
                    allowedTypes={['image']}
                    canEditImage={true}
                    labels={{
                        title: 'Select a Background Image',
                        instructions: 'Upload an image or pick one from your media library.'
                    }}
                />
                {backgroundImage && (
                    <Flex gap={2} direction={'column'}>
                        <FlexBlock>
                            <MediaReplaceFlow
                                mediaId={backgroundImage}
                                allowedTypes={['image']}
                                accept="image/*"
                                onSelect={onSelectBackgroundImage}
                            />
                        </FlexBlock>
                        <FlexBlock>
                            <Button onClick={onRemoveBackgroundImage} isDestructive icon="trash">
                                {__('Remove Media', 'lead-gen')}
                            </Button>
                        </FlexBlock>
                    </Flex>
                )}
                <hr />
                <MediaUploadCheck>
                    <MediaUpload
                        onSelect={onSelectBackgroundVideo}
                        allowedTypes={['video']}
                        value={backgroundVideo}
                        render={({ open }) => (
                            <Flex gap={2} direction={'column'}>
                                <FlexBlock>
                                    <Button
                                        onClick={open}
                                        variant={"secondary"}
                                    >
                                        {backgroundVideo ? __('Replace Background Video', 'lead-gen') : __('Select Background Video', 'lead-gen')}
                                    </Button>
                                </FlexBlock>
                                {backgroundVideo && (
                                    <FlexBlock>
                                        <Button
                                            onClick={onRemoveBackgroundVideo}
                                            isDestructive
                                            variant={"link"}
                                        >
                                            {__('Remove Background Video', 'lead-gen')}
                                        </Button>
                                    </FlexBlock>
                                )}
                            </Flex>
                        )}
                    />
                </MediaUploadCheck>
            </PanelBody>
            <PanelBody title={__('Background Overlay', 'lead-gen')} initialOpen={false}>
                <ToggleControl
                    label={__('Enable Background Overlay', 'lead-gen')}
                    checked={backgroundOverlay}
                    onChange={(val) => setAttributes({ backgroundOverlay: val })}
                />
                {backgroundOverlay && (
                    <>
                        <p style={{ marginTop: '1em', marginBottom: '0.5em' }}>
                            {__('Overlay Color', 'lead-gen')}
                        </p>
                        <ColorPicker
                            color={backgroundOverlayColor || '#000000'}
                            onChangeComplete={(value) => {
                                if (value?.hex) {
                                    setAttributes({ backgroundOverlayColor: value.hex });
                                }
                            }}
                        />
                    </>
                )}
            </PanelBody>
            {isAdmin && (
                <PanelBody title={__('Placeholder Dimensions', 'lead-gen')} initialOpen={false}>
                    <Flex style={{ gap: '8px' }}>
                        <FlexBlock>
                            <TextControl
                                label={__('Width', 'lead-gen')}
                                type="number"
                                value={placeholderDimensions.width || ''}
                                onChange={(val) =>
                                    setAttributes({
                                        placeholderDimensions: {
                                            ...placeholderDimensions,
                                            width: val,
                                        },
                                    })
                                }
                            />
                        </FlexBlock>
                        <FlexBlock>
                            <TextControl
                                label={__('Height', 'lead-gen')}
                                type="number"
                                value={placeholderDimensions.height || ''}
                                onChange={(val) =>
                                    setAttributes({
                                        placeholderDimensions: {
                                            ...placeholderDimensions,
                                            height: val,
                                        },
                                    })
                                }
                            />
                        </FlexBlock>
                    </Flex>
                </PanelBody>
            )}
        </>
    );
}
