import { useEffect, useState, useRef, useCallback, useContext } from '@wordpress/element';
import noDataImg from '../../assets/32x32/empty-box.png';
import { generateFileItem, upgradeToProAlert, syncStorageUsage } from '../../utils/common';
import { __ } from '@wordpress/i18n';
import LightGallery from 'lightgallery/react';
import lgZoom from 'lightgallery/plugins/zoom';
import lgVideo from 'lightgallery/plugins/video';
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgAutoplay from 'lightgallery/plugins/autoplay';
import lgFullscreen from 'lightgallery/plugins/fullscreen';
import { showAlert } from '../../utils/alertHelper';
import Uploader from './Uploader';
import FileList from '../components/browser/FileList';
import FolderList from '../components/browser/FolderList';
import LoadingIndicator from '../components/LoadingIndicator';
import { decode } from 'js-base64';
import { ThemeContext } from '../Provider/Context';
import Header from '../../components/Header';
import Navbar from './Navbar';

const Browser = (props) => {
	const {
		sortBy,
		sortDirection,
		isLoading,
		setIsLoading,
		currentPath,
		previousPath,
		setPreviousPath,
		setPath,
		refresh,
		setRefresh,
		showUploader,
		setBreadcrumbs,
		showContexify,
		setShowDetails,
		setDetailsItem,
		setSelectedContent,
		setSelectedCards,
	} = useContext(ThemeContext);
	const {
		config = {},
		type,
		path = currentPath,
		// onFileClick,
		enableGallery = true,
		enableHeader = true,
		enableSelected = false,
		folderSelectOnly = false,
		selectedItems = {},
		selectedFolder = {},
		setSelectedItems = () => {},
		onFileClick = () => {},
		pData = [],
		isFormUploader = false,
		isSingleFolderSelector = false,
		enableFolderSelect = true,
		fileTypeFilter = null,
		activeAccount = null,
		fetchData = null,
		shortcodeId = null,
	} = props;

	const {
		showHeader = false,
		// showUploader = true,
		showBreadcrumb = true,
		showAccount = true,
		showMoreMenu = {
			show: true,
			showNewFolder: true,
			showUploader: true,
		},
		showFiles,
		showFolder = true,
		showFilter = true,
		showRefresh = true,
		className = '',
		shortCodeBuilder = false,
		enableUploader = true
	} = config;

	useEffect(() => {
		setSelectedContent([]);
		setSelectedCards([]);
	}, []);

	const [galleryItems, setGalleryItems] = useState([]);

	const lightGallery = useRef(null);
	const onInit = useCallback((detail) => {
		if (detail) {
			lightGallery.current = detail.instance;
		}
	}, []);

	let { activeAccount: activeAccountData, settings } = EDBIData;

	let initialActiveAccount;
	// Only use activeAccount prop if it has a valid id
	if (activeAccount) {
		initialActiveAccount = activeAccount;
	} else {
		// activeAccountData is base64 encoded JSON, need to decode AND parse
		try {
			initialActiveAccount = JSON.parse(decode(activeAccountData));
		} catch (e) {
			console.error('Error parsing active account data:', e, activeAccountData);
			initialActiveAccount = null;
		}
	}
	const [currentActiveAccount, setCurrentActiveAccount] = useState(initialActiveAccount);

	// Initialize data state with pData if provided (for pre-loaded data)
	const [data, setData] = useState(pData || []);

	const cacheRef = useRef(new Map());

	// Track if we've initialized with pData (for frontend pre-loaded sources)
	const pDataInitializedRef = useRef(false);
	// Track the initial path for source mode protection
	const initialPathRef = useRef(null);

	// Pre-cache pData if provided for the initial path (synchronous, before any useEffect)
	// This ensures cache is populated before the main fetch useEffect runs
	if (pData && pData.length > 0 && !pDataInitializedRef.current) {
		// Store the initial path to prevent unwanted AJAX calls
		initialPathRef.current = currentPath;
		const initialCacheKey = `${currentActiveAccount?.id || 'unknown'}:${currentPath}:${sortBy || 'name'}:${sortDirection || 'asc'}`;
		cacheRef.current.set(initialCacheKey, {
			files: pData,
			breadcrumbs: [{ name: 'Home', path: '/' }],
			previous_path: null,
		});
		pDataInitializedRef.current = true;
	}

	// Listen for account switch event and clear cache
	useEffect(() => {
		const handleAccountSwitched = (event) => {
			const newAccount = event.detail;
			if (newAccount) {
				// Update the active account state
				setCurrentActiveAccount(newAccount);
				// Clear the cache when account is switched
				cacheRef.current.clear();
				// Clear Bulk Select.
				setSelectedContent([]);
				setSelectedCards([]);
			}
		};

		window.addEventListener('edbi_account_switched', handleAccountSwitched);

		return () => {
			window.removeEventListener('edbi_account_switched', handleAccountSwitched);
		};
	}, []);

	useEffect(() => {
		if (
			!currentActiveAccount ||
			typeof currentActiveAccount !== 'object' ||
			!currentActiveAccount.id
			// || !currentPath ||
			// currentPath.trim() === ''
		) {
			return;
		}

		const filter = {
			by: sortBy || 'name',
			direction: sortDirection || 'asc',
		};

		const cacheKey = `${currentActiveAccount.id}:${currentPath}:${sortBy}:${sortDirection}`;
		const cached = cacheRef.current.get(cacheKey);

		// ✅ Check if we're in source mode and on initial path - prevent unwanted AJAX
		// When source mode is active and we're on the initial path, never make AJAX calls
		const isSourceMode = pDataInitializedRef.current;
		const isOnInitialPath = initialPathRef.current !== null && currentPath === initialPathRef.current;
		const shouldSkipAjax = isSourceMode && isOnInitialPath;

		if (shouldSkipAjax && refresh) {
			// In source mode on initial path: use cached data even when refresh is true
			// This prevents fetching ALL files from Dropbox when refresh is clicked
			const sourceCache = cacheRef.current.get(cacheKey);
			if (sourceCache) {
				const files = Array.isArray(sourceCache) ? sourceCache : (sourceCache.files || []);
				setData(files);
				setBreadcrumbs(Array.isArray(sourceCache) ? [] : (sourceCache.breadcrumbs || []));
				setPreviousPath(Array.isArray(sourceCache) ? null : (sourceCache.previous_path || null));

				const galleryItems = files
					.filter((item) => item.is_file)
					.map((file) => generateFileItem(file, 'browser'));
				setGalleryItems(galleryItems);

				setIsLoading(false);
				setRefresh(false); // Reset refresh state
				return;
			}
		}

		// ✅ If data is cached (including pre-loaded pData), use it
		if (cached && !refresh) {
			// Handle both old cache format (array) and new cache format (object)
			const files = Array.isArray(cached) ? cached : (cached.files || []);
			setData(files);
			setBreadcrumbs(Array.isArray(cached) ? [] : (cached.breadcrumbs || []));
			setPreviousPath(Array.isArray(cached) ? null : (cached.previous_path || null));

			const galleryItems = files
				.filter((item) => item.is_file)
				.map((file) => generateFileItem(file, 'browser'));
			setGalleryItems(galleryItems);

			setIsLoading(false);
			return;
		}

		// 🚀 Fetch from API using WordPress AJAX.
		// fetchData callback should return: { files, breadcrumbs, previous_path }
		let fetchPromise;

		if (fetchData) {
			fetchPromise = fetchData({
				path: currentPath,
				accountId: currentActiveAccount.id,
				filter: filter,
				refresh: refresh,
				shortcodeId: shortcodeId,
			});
		} else {
			const ajaxData = {
				path: currentPath,
				account_id: currentActiveAccount.id,
				filter: filter,
				refresh: refresh,
				nonce: EDBIData.ajaxNonce,
			};
			// Include shortcode_id if available for backend source validation
			if (shortcodeId) {
				ajaxData.shortcode_id = shortcodeId;
			}
			fetchPromise = new Promise((resolve, reject) => {
				wp.ajax.post('edbi_get_files', ajaxData).done(resolve).fail((xhr) => {
					reject(new Error(xhr.responseJSON?.message || xhr.statusText || 'Failed to fetch data.'));
				});
			});
		}

		fetchPromise
			.then((response) => {
				// Handle multiple response formats:
				// 1. Direct format (preferred for fetchData): {files, breadcrumbs, previous_path}
				// 2. Wrapped format (REST API/apiFetch): {success: true, data: {files, ...}}
				let files, breadcrumbs, previousPath;
				if (response?.success && response?.data) {
					// Wrapped format (REST API/apiFetch)
					files = response.data.files;
					breadcrumbs = response.data.breadcrumbs || [];
					previousPath = response.data.previous_path || null;
				} else {
					// Direct format (wp.ajax.post or fetchData callback)
					files = response?.files;
					breadcrumbs = response?.breadcrumbs || [];
					previousPath = response?.previous_path || null;
				}


				console.log('response', response)

				if (!files || !Array.isArray(files)) {
					console.warn('⚠️ No files received, not caching');
					setData([]);
					setBreadcrumbs([]);
					setPreviousPath(null);
					setGalleryItems([]);
					setIsLoading(false);
					return;
				}

				setData(files);
				// Cache full response for complete restoration (performance optimization)
				cacheRef.current.set(cacheKey, {
					files: files,
					breadcrumbs: breadcrumbs,
					previous_path: previousPath,
				});

				setBreadcrumbs(breadcrumbs);
				setPreviousPath(previousPath);

				const galleryItems = files
					.filter((item) => item.is_file)
					.map((file) => generateFileItem(file));
				setGalleryItems(galleryItems);

				setIsLoading(false);
			})
			.catch((err) => {
				console.error(err);
				showAlert({
					title: 'Error',
					text: err.message || 'Failed to fetch data.',
					icon: 'error',
				});
				setIsLoading(false);
			});
	}, [currentPath, refresh, sortBy, sortDirection, currentActiveAccount.id]);

	let folders;
	let files;
	if (data.length) {
		folders = data.filter((item) => item.is_dir);

		files = data.filter((item) => {
			if (!item.is_file) {
				return false;
			}

			// Apply file type filter if provided
			if (fileTypeFilter) {
				const ext = item.ext ? item.ext.toLowerCase() : '';
				const mimeType = item.mimetype || '';

				// Check for custom filter object (e.g., { types: ['image', 'video'] })
				if (typeof fileTypeFilter === 'object' && fileTypeFilter.types) {
					const allowedTypes = fileTypeFilter.types;

					// Check if this file matches any of the allowed types
					return allowedTypes.some((allowedType) => {
						switch (allowedType) {
							case 'image':
								return ext.match(/(jpg|jpeg|png|gif|webp|bmp|svg|ico)$/i) ||
									mimeType.startsWith('image/');
							case 'video':
								return ext.match(/(mp4|mov|avi|mkv|webm|flv|wmv|m4v)$/i) ||
									mimeType.startsWith('video/');
							case 'audio':
								return ext.match(/(mp3|wav|ogg|flac|aac|m4a|wma)$/i) ||
									mimeType.startsWith('audio/');
							default:
								return false;
						}
					});
				}

				// Handle string-based filters
				switch (fileTypeFilter) {
					case 'image':
						return ext.match(/(jpg|jpeg|png|gif|webp|bmp|svg|ico)$/i) ||
							mimeType.startsWith('image/');
					case 'video':
						return ext.match(/(mp4|mov|avi|mkv|webm|flv|wmv|m4v)$/i) ||
							mimeType.startsWith('video/');
					case 'audio':
						return ext.match(/(mp3|wav|ogg|flac|aac|m4a|wma)$/i) ||
							mimeType.startsWith('audio/');
					case 'media':
						const isImage = ext.match(/(jpg|jpeg|png|gif|webp|bmp|svg|ico)$/i) ||
							mimeType.startsWith('image/');
						const isVideo = ext.match(/(mp4|mov|avi|mkv|webm|flv|wmv|m4v)$/i) ||
							mimeType.startsWith('video/');
						const isAudio = ext.match(/(mp3|wav|ogg|flac|aac|m4a|wma)$/i) ||
							mimeType.startsWith('audio/');
						return isImage || isVideo || isAudio;
					case 'document':
						return ext.match(/(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|rtf|odt|ods|odp)$/i);
					default:
						// If it's a custom regex pattern
						if (fileTypeFilter instanceof RegExp) {
							return ext.match(fileTypeFilter);
						}
						return true;
				}
			}

			return true;
		});
	} else {
		folders = [];
		files = [];
	}

	const handleItemClick = ({ id, event, props }) => {
		const { item, index } = props.data;

		switch (id) {
			case 'preview':
				if (!item.can_preview) {
					showAlert({
						title: __('Error', 'easy-dropbox-integration'),
						text: __('File cannot be previewed.', 'easy-dropbox-integration'),
						icon: 'error',
					});
					return;
				}
				lightGallery.current.openGallery(index);
				break;
			case 'preview-in-new-window':
				if (!item.can_preview) {
					showAlert({
						title: __('Error', 'easy-dropbox-integration'),
						text: __('File cannot be previewed.', 'easy-dropbox-integration'),
						icon: 'error',
					});
					return;
				}
				const url =
					EDBIData.ajaxUrl +
					'?action=edbi_file_preview&account_id=' +
					(item.account_id || currentActiveAccount.id) +
					'&nonce=' +
					EDBIData?.ajaxNonce +
					'&id=' +
					item.id;

				window.open(url, '_blank');

				break;
			case 'rename':
				showAlert({
					title: __('Rename', 'easy-dropbox-integration'),
					html: `
					<div className="edbi-swal2-html-container">
					<p className="edbi-swal2-title">${__('Enter new name', 'easy-dropbox-integration')}</p>
					<div>
						<input id="swal-rename-input" class="swal2-input" value="${item.name}" />
					</div>
					</div>
				`,
					confirmButtonText: __('Rename', 'easy-dropbox-integration'),
				}).then((result) => {
					console.log(currentPath);
					if (result.isConfirmed) {
						const newName = document.getElementById('swal-rename-input').value;
						// Build full path for new name
						const newPath = currentPath === '/' ? `/${newName}` : `${currentPath}/${newName}`;

						console.log('currentActiveAccount', currentActiveAccount)
						wp.ajax
							.post('edbi_rename', {
								account_id: item.account_id || currentActiveAccount.id,
								nonce: EDBIData?.ajaxNonce,
								old_name: item.path,
								new_name: newPath,
							})
							.then((response) => {
								// Check if response indicates success or error
								if (response.success === false) {
									showAlert({
										title: __('Error', 'easy-dropbox-integration'),
										text: response.message || __('Failed to rename', 'easy-dropbox-integration'),
										icon: 'error',
									});
								} else {
									showAlert({
										title: __('Success', 'easy-dropbox-integration'),
										text: response.message,
										icon: 'success',
									});

									// Dispatch an action to refresh the browser.
									setRefresh(true);
								}
							})
							.catch((error) => {
								showAlert({
									title: __('Error', 'easy-dropbox-integration'),
									text: error.message || __('Failed to rename', 'easy-dropbox-integration'),
									icon: 'error',
								});
							});
					}
				});
				break;
			case 'open':
				wp.ajax
				.post('edbi_direct_link', {
					account_id: item.account_id || currentActiveAccount.id,
					nonce: EDBIData?.ajaxNonce,
					id: item.id,
				})
				.then((response) => {
					// Check if response indicates success or error
					if (response.success === false) {
						showAlert({
							title: __('Error', 'easy-dropbox-integration'),
							text: response.message || __('Failed to get direct link', 'easy-dropbox-integration'),
							icon: 'error',
						});
					} else {
						const decodedLink = decodeURIComponent(response);
						window.open(decodedLink, '_blank');
					}
				})
				.catch((error) => {
					showAlert({
						title: __('Error', 'easy-dropbox-integration'),
						text: error.message || __('Failed to get direct link', 'easy-dropbox-integration'),
						icon: 'error',
					});
				});
				break;
			case 'direct-link':

				showAlert({
					text: __('Opening in New Tab', 'easy-dropbox-integration'),
					icon: 'info',
					toast: true,
					position: 'top-end',
					showConfirmButton: false,
					timer: 2000,
				});

				wp.ajax
				.post('edbi_direct_link', {
					account_id: item.account_id || currentActiveAccount.id,
					nonce: EDBIData?.ajaxNonce,
					id: item.id,
				})
				.then((response) => {
					// Check if response indicates success or error
					if (response.success === false) {
						showAlert({
							title: __('Error', 'easy-dropbox-integration'),
							text: response.message || __('Failed to get direct link', 'easy-dropbox-integration'),
							icon: 'error',
						});
					} else {
						const decodedLink = decodeURIComponent(response);
						window.open(decodedLink, '_blank');
					}
				})
				.catch((error) => {
					showAlert({
						title: __('Error', 'easy-dropbox-integration'),
						text: error.message || __('Failed to get direct link', 'easy-dropbox-integration'),
						icon: 'error',
					});
				});

				break;
			case 'share':
				showAlert({
					title: __('Coming Soon!', 'easy-dropbox-integration'),
					text: __('This feature is coming soon, InshAllah!', 'easy-dropbox-integration'),
					icon: 'info',
				});
				break;
			case 'move':
				showAlert({
					title: __('Coming Soon!', 'easy-dropbox-integration'),
					text: __('This feature is coming soon, InshAllah!', 'easy-dropbox-integration'),
					icon: 'info',
				});
				break;
			case 'duplicate':
				showAlert({
					title: __('Coming Soon!', 'easy-dropbox-integration'),
					text: __('This feature is coming soon, InshAllah!', 'easy-dropbox-integration'),
					icon: 'info',
				});
				break;
			case 'details':
				setShowDetails(true);
				setDetailsItem(item);
				break;
			case 'import':
				// Check if pro version is active.
				if (!EDBIData?.isPro || '1' !== EDBIData?.isPro) {
					upgradeToProAlert();
					break;
				}

				showAlert({
					title: __('Importing', 'easy-dropbox-integration'),
					text: __(
						'Your import is being prepared. You will be notified once it is ready.',
						'easy-dropbox-integration'
					),
					icon: 'info',
					toast: true,
					position: 'top-end',
					showConfirmButton: false,
					timer: 3000,
				});

				wp.ajax
					.post('edbi_import_file', {
						account_id: item.account_id || currentActiveAccount.id,
						nonce: EDBIData?.ajaxNonce,
						id: item.id,
					})
					.then((response) => {
						// Check if response indicates success or error
						if (response.success === false) {
							showAlert({
								title: __('Error', 'easy-dropbox-integration'),
								text: response.message || __('Failed to import file', 'easy-dropbox-integration'),
								icon: 'error',
							});
						} else {
							showAlert({
								title: __('Success', 'easy-dropbox-integration'),
								text: response.message,
								icon: 'success',
							});
						}
					})
					.catch((error) => {
						showAlert({
							title: __('Error', 'easy-dropbox-integration'),
							text: error.message || __('Failed to import file', 'easy-dropbox-integration'),
							icon: 'error',
						});
					});
				break;

			case 'download':
				const downloadUrl = `${EDBIData.ajaxUrl}?action=edbi_download_file&account_id=${item.account_id || currentActiveAccount.id}&nonce=${EDBIData?.ajaxNonce}&id=${item.id}`;

				// open url in new tab.
				window.open(downloadUrl, '_blank');

				break;

			case 'download-as-zip':
				// Add a toast notification that the zip is being prepared.
				showAlert({
					title: __('Preparing Download', 'easy-dropbox-integration'),
					text: __(
						'Your download is being prepared. You will be notified once it is ready.',
						'easy-dropbox-integration'
					),
					icon: 'info',
					toast: true,
					position: 'top-end',
					showConfirmButton: false,
					timer: 3000,
				});

				wp.ajax
					.post('edbi_download_as_zip', {
						account_id: item.account_id || currentActiveAccount.id,
						nonce: EDBIData?.ajaxNonce,
						folder_id: item.id,
					})
					.then((response) => {
						// Check if response indicates success or error
						if (response.success === false) {
							showAlert({
								title: __('Error', 'easy-dropbox-integration'),
								text: response.message || __('Failed to download as zip', 'easy-dropbox-integration'),
								icon: 'error',
							});
						} else {
							const zipDownloadUrl = response.data;

							// Download the zip file without opening a new tab.
							const link = document.createElement('a');
							link.href = zipDownloadUrl;
							link.download = `${item.name}.zip`;
							link.click();
							link.remove();

							showAlert({
								title: __('Success', 'easy-dropbox-integration'),
								text: response.message,
								icon: 'success',
							});
						}
					})
					.catch((error) => {
						showAlert({
							title: __('Error', 'easy-dropbox-integration'),
							text: error.message || __('Failed to download as zip', 'easy-dropbox-integration'),
							icon: 'error',
						});
					});

				break;
			case 'cut':
				showAlert({
					title: __('Coming Soon!', 'easy-dropbox-integration'),
					text: __('This feature is coming soon, InshAllah!', 'easy-dropbox-integration'),
					icon: 'info',
				});
				break;
			case 'delete':
				showAlert({
					title: __('Are you sure?', 'easy-dropbox-integration'),
					html: `
					<h4 style="color:red; margin-top: 10px">${__(
						"You won't be able to revert this!",
						'easy-dropbox-integration'
					)}</h4>
				`,
					showCancelButton: true,

					confirmButtonText: __('Yes, delete it!', 'easy-dropbox-integration'),
				}).then((result) => {
					if (result.isConfirmed) {
						wp.ajax
							.post('edbi_delete', {
								account_id: item.account_id || currentActiveAccount.id,
								nonce: EDBIData?.ajaxNonce,
								path: item.path,
							})
							.then(async (response) => {
								// Check if response indicates success or error
								if (response.success === false) {
									showAlert({
										title: __('Error', 'easy-dropbox-integration'),
										text: response.message || __('Failed to delete', 'easy-dropbox-integration'),
										icon: 'error',
									});
								} else {
									showAlert({
										title: __('Deleted!', 'easy-dropbox-integration'),
										text: response.message || __(
											'Your file has been deleted',
											'easy-dropbox-integration'
										),
										icon: 'success',
									});

									await syncStorageUsage();

									// Dispatch an action to refresh the browser.
									setRefresh((prev) => !prev);
								}
							})
							.catch((error) => {
								showAlert({
									title: __('Error', 'easy-dropbox-integration'),
									text: error.message || __('Failed to delete', 'easy-dropbox-integration'),
									icon: 'error',
								});
							});
					}
				});
				break;
		}
	};

	// Determine if we should show empty state and what message to display
	const renderEmptyState = () => {
		// Completely empty - no folders and no files
		if (folders.length === 0 && files.length === 0) {
			return (
				<div className='edbi-empty-box'>
					<img
						src={noDataImg}
						alt={__('Nothing found!', 'easy-dropbox-integration')}
					/>
					<p className=''>
						{__('Nothing found! or try to refresh by clicking on refresh button', 'easy-dropbox-integration')}
					</p>
				</div>
			);
		}

		// Folder-only mode with no folders (but files exist)
		if (enableFolderSelect && folders.length === 0) {
			return (
				<div className='edbi-empty-box'>
					<img
						src={noDataImg}
						alt={__('No folders found', 'easy-dropbox-integration')}
					/>
					<p className=''>
						{__('No folders found in this location', 'easy-dropbox-integration')}
					</p>
				</div>
			);
		}

		// File type filter is active and no matching files
		if (fileTypeFilter && files.length === 0) {
			let filterMessage = __('No matching files found', 'easy-dropbox-integration');

			// More specific messages for different filter types
			if (typeof fileTypeFilter === 'object' && fileTypeFilter.types) {
				const types = fileTypeFilter.types;
				if (types.includes('image') && types.includes('video')) {
					filterMessage = __('No images or videos found', 'easy-dropbox-integration');
				} else if (types.includes('audio') && types.includes('video')) {
					filterMessage = __('No media files found', 'easy-dropbox-integration');
				} else if (types.includes('image')) {
					filterMessage = __('No images found', 'easy-dropbox-integration');
				} else if (types.includes('video')) {
					filterMessage = __('No videos found', 'easy-dropbox-integration');
				} else if (types.includes('audio')) {
					filterMessage = __('No audio files found', 'easy-dropbox-integration');
				}
			} else if (typeof fileTypeFilter === 'string') {
				switch (fileTypeFilter) {
					case 'image':
						filterMessage = __('No images found', 'easy-dropbox-integration');
						break;
					case 'video':
						filterMessage = __('No videos found', 'easy-dropbox-integration');
						break;
					case 'audio':
						filterMessage = __('No audio files found', 'easy-dropbox-integration');
						break;
					case 'media':
						filterMessage = __('No media files found', 'easy-dropbox-integration');
						break;
					case 'document':
						filterMessage = __('No documents found', 'easy-dropbox-integration');
						break;
				}
			}

			return (
				<div className='edbi-empty-box'>
					<img
						src={noDataImg}
						alt={filterMessage}
					/>
					<p className=''>{filterMessage}</p>
				</div>
			);
		}

		return null;
	};

	return (
		<>
			{/* <Navbar
				showSearch={true}
				showFilter={true}
				showAccount={true}
				showRefresh={true}
				showMoreMenu={{
					show: true,
					showNewFolder: true,
					showUpload: true,
					showDownload: true,
					showDelete: true,
					showShare: true,
				}}
			/> */}
			<div className='edbi-browser'>
				{ enableUploader && showUploader && (
					<Uploader
						path={path}
						filters={{
							allowAllExtension: true,
							allowedExtensions: '',
							allowedExceptExtensions: '',
							showFolders: true,
							showFiles: true,
						}}
						// maxFileSize={''}
						// maxFiles={''}
						// minFileSize={''}
						allowFolderUpload={true}
						// uploadImmediately={false}
						onUpload={(file) => {
							// console.log('on upload', file);
						}}
						showUploadConfirmation={false}
						isFormUploader={false}
						isMainUploader={true}
					/>
				)}

				<div>
					{ settings?.advanced?.ownApp?.appSecret !== '' && settings?.advanced?.ownApp?.clientID !== '' ? (
						!currentActiveAccount || !currentActiveAccount.id ? (
							<>
								<div className='edbi-no-account edbi-badge edbi-badge--info'>
									<h3>{__('No Accounts', 'easy-dropbox-integration')}</h3>
									<p>{__('Please add a Dropbox account', 'easy-dropbox-integration')}</p>

									<button
										onClick={() => {
											window.open(
												EDBIData.authUrl,
												'_blank',
												'width=600,height=600,toolbar=yes,scrollbars=yes,resizable=yes'
											);
										}}
										className='edbi-btn edbi-btn--primary'
									>
										{__('Add Account', 'easy-dropbox-integration')}
									</button>
								</div>
							</>
						) : (
							<div style={{ flex: 1 }}>
								{showHeader && <Header config={config} />}

								{isLoading && <LoadingIndicator />}

								{!isLoading && (
									<FolderList
										folders={folders}
										previousPath={previousPath}
										setPath={setPath}
										showContexify={showContexify}
										showMoreMenu={showMoreMenu}
										enableFolderSelect={ enableFolderSelect }
										handleItemClick={handleItemClick}
										allowBulkMode={config.allowBulkMode}
										shortcodeBuilder={config.shortcodeBuilder}
										selectedItems={selectedItems}
										isFormUploader={isFormUploader}
										isSingleFolderSelector={isSingleFolderSelector}
									/>
								)}

								{!isLoading && (
									<FileList
										files={files}
										lightGallery={lightGallery}
										showContexify={showContexify}
										showMoreMenu={showMoreMenu}
										onFileClick={onFileClick}
										enableGallery={enableGallery}
										handleItemClick={handleItemClick}
										shortcodeBuilder={config.shortcodeBuilder}
										showFiles={config.showFiles}
										enableSelected={enableSelected}
										selectedItems={selectedItems}
									/>
								) }

								{!isLoading && renderEmptyState()}
							</div>
						)
					) : (
						<div className='edbi-no-account edbi-badge edbi-badge--info'>
							<h3>{__('Connection Required', 'easy-dropbox-integration')}</h3>
							<p>{__('Please configure your App Key & App Secret', 'easy-dropbox-integration')}</p>

							<button
								onClick={() => {
									window.location.href = EDBIData.connectDropboxUrl;
								}}
								className='edbi-btn edbi-btn--primary'
							>
								{__('Connect Dropbox', 'easy-dropbox-integration')}
							</button>
						</div>
					)}
				</div>

				{enableGallery && (
					<LightGallery
						onInit={onInit}
						elementClassNames={'gallery'}
						dynamic={true}
						plugins={[lgZoom, lgVideo, lgThumbnail, lgAutoplay, lgFullscreen]}
						licenseKey='DEC07C11-66CA-441B-91EB-78600E170147'
						dynamicEl={galleryItems}
						onSlideItemLoad={(item) => {
							const downloadElements = document.querySelectorAll('.lg-download');
							downloadElements.forEach(function (element) {
								element.removeAttribute('download');
							});
						}}
					></LightGallery>
				)}
			</div>
		</>
	);
};

export default Browser;
