import { createRoot } from '@wordpress/element';
import { Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { showAlert } from '../../../utils/alertHelper';
import { decode } from 'js-base64';
import { GoTrash } from 'react-icons/go';
import { FaFolderPlus } from 'react-icons/fa';
import { RiFolderMusicFill } from 'react-icons/ri';


const MediaLibrary = (props) => {
	const { settings, setSettings } = props;

	let { activeAccount: activeAccountData } = EDBIData;
	let activeAccount;
	try {
		activeAccount = typeof activeAccountData === 'string' ? JSON.parse(decode(activeAccountData)) : activeAccountData;
	} catch (e) {
		console.error('Error parsing active account:', e);
		activeAccount = null;
	}
	// Clear attachments function using ajax call
	const clearAttachments = () => {
		wp.ajax
			.post('edbi_clear_attachments', {
				nonce: EDBIData?.ajaxNonce,
				account_id: activeAccount.id,
			})
			.then(() => {
				showAlert({
					type: 'success',
					title: __('Success', 'easy-dropbox-integration'),
					text: __('Attachments cleared successfully', 'easy-dropbox-integration'),
					icon: 'success',
					showCancelButton: false,
					confirmButtonText: 'Ok',
				});
			});
	};

	// Open the folder selection modal
	const openFolder = () => {
		Swal.fire({
			customClass: 'edbi-swal-modal',
			title: __('Select Folder', 'easy-dropbox-integration'),
			html: '<div id="edbi-folder-selection"></div>',
			showConfirmButton: false,
			title: false,
			didOpen: () => {
				const root = document.getElementById('edbi-folder-selection');
				let reactRoot = null;

				const RootComponent = () => {
					return (
						<window.EDBIFileBrowser
							title={__('Media Library Configure', 'easy-dropbox-integration')}
							onDone={(selectedItems) => {
								setSettings({
									...settings,
									mediaLibrary: selectedItems?.folders || [],
								});
								Swal.close();
							}}
							onClose={() => {
								Swal.close();
							}}
							config={{
								showHeader: true,
								showUploader: false,
								showBreadcrumb: true,
								showAccount: false,
								showMoreMenu: false,
								showFiles: false,
								showFolder: true,
								className: 'not-fixed-header',
							}}
							folderSelectOnly={true}
							enableFolderSelect={true}
							enableSelected={true}
							enableGallery={false}
							initialSelectedItems={{
								files: [],
								folders: settings?.mediaLibrary || [],
							}}
						/>
					)
				}
				if (root) {
					reactRoot = createRoot(root);
					reactRoot.render(<RootComponent />);
				}
				
				// Attach cleanup to the swal instance or handle it via willClose
				Swal.getPopup().reactRoot = reactRoot;
			},
			willClose: () => {
				const popup = Swal.getPopup();
				if (popup && popup.reactRoot) {
					popup.reactRoot.unmount();
				}
			}
		});
	};

	return (
		<>
			<div className="edbi-settings-header">
				<div className="edbi-settings-header__title-wrapper">
					<h3>
						<RiFolderMusicFill style={{ marginRight: '10px' }} />
						{__('Media Library Settings', 'easy-dropbox-integration')}
					</h3>
					<div className="edbi-settings-description">
						{__(
							'Configure media library settings for your website.',
							'easy-dropbox-integration'
						)}
					</div>
				</div>
			</div>
			
			<div className='edbi-flex'>
				<div className='edbi-settings-fields__item'>
					<div className='edbi-shortcode-builder__container'>
						{/* <h3 className='edbi-shortcode-appearance-title'>
							{__('Media Library Folder', 'easy-dropbox-integration')}
						</h3> */}
						<h3 className='edbi-settings-tools__title'>
							{__('Media Library Folder', 'easy-dropbox-integration')}
						</h3>
						
						<Button className='edbi-button edbi-button--primary edbi-settings-tools__btn' onClick={openFolder}>
							<FaFolderPlus style={{ fontSize: '1.2em' }} />
							{__('Select Folder', 'easy-dropbox-integration')}
						</Button>

						<div className='edbi-flex edbi-selected-folders'>
							{settings?.mediaLibrary?.length ?
								settings?.mediaLibrary?.map((item, index) => (
								<span
									key={index}
									className='edbi-badge edbi-badge--info'
									style={{
										padding: '5px 10px',
									}}
								>
									{item.name}
								</span>
							)) : ''}
						</div>

					</div>
				</div>

				<div className='edbi-settings-fields__item'>
					<div className='edbi-shortcode-builder__container'>
						<h3 className='edbi-settings-tools__title'>
							{__('Clear Attachments', 'easy-dropbox-integration')}
						</h3>
						<Button className='edbi-button edbi-button--warning edbi-settings-tools__btn' onClick={clearAttachments}>
							<GoTrash style={{ fontSize: '1.2em' }} />
							{__('Clear Attachments', 'easy-dropbox-integration')}
						</Button>
					</div>
				</div>
			</div>
		</>
	);
};

export default MediaLibrary;
