import { MdOutlineKeyboardArrowRight } from 'react-icons/md';
import { RxHome } from 'react-icons/rx';
import { CiSearch } from 'react-icons/ci';
import { HiOutlineArrowSmallLeft, HiOutlineBarsArrowDown } from 'react-icons/hi2';
import { FiRefreshCw, FiUploadCloud } from 'react-icons/fi';
import { TbDotsVertical, TbLayoutGrid, TbListDetails } from 'react-icons/tb';
import { useContext, useEffect, useRef, useState } from '@wordpress/element';
import { ThemeContext } from '../Provider/Context';
import { VscInfo, VscNewFolder } from 'react-icons/vsc';
import { GoCheckCircleFill, GoPlus } from 'react-icons/go';
import FilterDropdown from './FilterDropdown';
// import logo from '../../../assets/images/file-browser/ultradevs-logo.png';
import { RiMenu3Fill } from 'react-icons/ri';
import { decode } from 'js-base64';

import { __ } from '@wordpress/i18n';

import Header from './browser/Header';
import { HiOutlineChevronRight } from 'react-icons/hi';
import MultipleItemAction from './MultipleItemAction';
import { showAlert } from '../../utils/alertHelper';

const Navbar = (props) => {
	const {
		gridView,
		setGridView,
		setIsLoading,
		setIsDrawerOpen,
		previousPath,
		setPath,
		currentPath,
		hideSidebar,
		setHideSidebar,
		setRefresh,
		isLoading,
		sortBy,
		setShowUploader,
		bulkMode,
		setBulkMode,
		selectedCards,
		setSelectedCards,
		setShowDetails,
	} = useContext(ThemeContext);

	const [dropdownFilter, setDropdownFilter] = useState(false);
	const [dropdownAction, setDropdownAction] = useState(false);
	const profileRef = useRef(null);
	const filterRef = useRef(null);
	const buttonRef = useRef(null);
	const actionRef = useRef(null);
	const actionButtonRef = useRef(null);

	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;
	}

	const toggleDropdownFilter = () => {
		setDropdownFilter(!dropdownFilter);
	};
	const toggleDropdownAction = () => {
		setDropdownAction(!dropdownAction);
	};

	useEffect(() => {
		const handleClickOutside = (event) => {
			if (
				filterRef.current &&
				!filterRef.current.contains(event.target) &&
				!buttonRef.current.contains(event.target) // ignore button
			) {
				setDropdownFilter(false);
			}

			if (
				actionRef.current &&
				!actionRef.current.contains(event.target) &&
				!actionButtonRef.current.contains(event.target) // ignore button
			) {
				setDropdownAction(false);
			}
		};

		document.addEventListener('mousedown', handleClickOutside);
		return () => {
			document.removeEventListener('mousedown', handleClickOutside);
		};
	}, []);

	const pathParts = currentPath.split('/').filter(Boolean);
	const titleCase = (str) =>
		str
			.split(' ')
			.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
			.join(' ');

	// const switchAccount = (id) => {
	// 	apiFetch({
	// 		path: '/edbi/v1/switch-account',
	// 		method: 'POST',
	// 		data: {
	// 			id: id,
	// 		},
	// 	}).then((response) => {
	// 		if ('success' === response.status) {
	// 			setRefresh(true);
	// 			setIsLoading(true);
	// 		}
	// 		// Reload the page.
	// 		window.location.reload();
	// 	});
	// };
	const toggleBulkMode = () => {
		setBulkMode((prev) => !prev);
		setSelectedCards([]);
	};

	const handleCreateFolder = () => {
		showAlert({
			title: __('New Folder', 'easy-dropbox-integration'),
			html: `
					<p>${__('Enter folder name', 'easy-dropbox-integration')}</p>
					<div>
						<input id="swal-new-folder-input" className="swal2-input" placeholder="Create New Folder" />
					</div>
				`,
			confirmButtonText: __('Create', 'easy-dropbox-integration'),
		}).then((result) => {
			if (result.isConfirmed) {
				wp.ajax
					.post('edbi_create_folder', {
						account_id: activeAccount['id'],
						nonce: EDBIData?.ajaxNonce,
						path: currentPath,
						name: document.getElementById('swal-new-folder-input').value,
					})
					.then((response) => {
						// Check if response indicates success or error
						if (response.success === false) {
							showAlert({
								title: __('Error', 'easy-dropbox-integration'),
								text: response.message || __('Failed to create folder', '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((prev) => !prev);
							setIsLoading(true);
						}
					})
					.catch((error) => {
						showAlert({
							title: __('Error', 'easy-dropbox-integration'),
							text: error.message || __('Failed to create folder', 'easy-dropbox-integration'),
							icon: 'error',
						});
					});
			}
		});
	};

	return (
		<nav className='edbi-navbar'>
			<div className='edbi-navbar-top'>
				<div className='edbi-navbar-top-left-mobile'>
					<RiMenu3Fill
						onClick={() => setIsDrawerOpen(true)}
						className='edbi-menu-icon-sm'
					/>
					<img
						className='edbi-logo-mobile'
						src={`${EDBIData?.assets}/images/edbi.png`}
						alt={__('Company Logo', 'easy-dropbox-integration')}
					/>
				</div>
				<div className='edbi-navbar-top-left'>
					{hideSidebar && (
						<div className='edbi-sidebar-opener'>
							<button onClick={() => setHideSidebar(false)}>
								<HiOutlineChevronRight />
							</button>
						</div>
					)}
					<span
						onClick={() => {
							currentPath !== '/' && setPath('/');
						}}
						className={`edbi-breadcrumb ${
							currentPath === '/' || currentPath === ''
								? 'edbi-breadcrumb-active'
								: ''
						} ${hideSidebar && 'edbi-margin-left'}`}
					>
						<RxHome />
						<h6 style={{ marginLeft: '2px' }}>
							{__('Home', 'easy-dropbox-integration')}
						</h6>
					</span>

					{pathParts.map((part, index) => {
						const pathUpToHere = '/' + pathParts.slice(0, index + 1).join('/');

						return (
							<span
								key={index}
								onClick={() => setPath(pathUpToHere)}
								className={`edbi-breadcrumb ${
									pathUpToHere === currentPath ? 'edbi-breadcrumb-active' : ''
								}`}
							>
								<MdOutlineKeyboardArrowRight />
								<h6>{__(titleCase(part), 'easy-dropbox-integration')}</h6>
							</span>
						);
					})}
				</div>
				<div className='edbi-navbar-top-right'>
					{
						props.showSearch && (
							<div className='edbi-search-container'>
								<CiSearch className='edbi-search-icon' />
								<input
									name='search'
									className='search-input'
									type='text'
									placeholder={__('Search', 'easy-dropbox-integration')}
								/>
							</div>
						)
					}
					{/* <button onClick={() => toggleDropdown()} className='edbi-navbar-top-right-button'>
						<img src={activeAccount?.photo} alt='User Image' />
						<h6>{activeAccount?.name}</h6>
						<MdOutlineKeyboardArrowDown
							className={`edbi-profile-dropdown-icon ${
								dropdownOpen ? 'rotate' : 'edbi-rerotate'
							}`}
						/>
					</button> */}

					<Header
						config={{
							showBreadCrumb: props.showBreadCrumb,
							showFilter: props.showFilter,
							showAccount: props.showAccount,
							showRefresh: props.showRefresh,
							showMoreMenu: {
								show: props.showMoreMenu,
								showNewFolder: props.showNewFolder,
								showUploader: props.showUploader,
							},
						}}
					/>
				</div>
			</div>

			<section className='edbi-navbar-bottom'>
				<div className='edbi-navbar-bottom-left'>
					{previousPath && currentPath !== '/' && (
						<div
							className='back-button-div'
							onClick={() => {
								currentPath !== '/' && setPath(previousPath);
							}}
						>
							<HiOutlineArrowSmallLeft className='edbi-nav-bottom-icon back-icon' />
						</div>
					)}

					<div ref={buttonRef} onClick={toggleDropdownFilter} className='edbi-filter'>
						<HiOutlineBarsArrowDown className='edbi-nav-bottom-icon' />
						<span>{__(titleCase(sortBy), 'easy-dropbox-integration')}</span>
						{dropdownFilter && <FilterDropdown filterRef={filterRef} />}
					</div>

					<label className='chk-label'>
						<input type='checkbox' checked={bulkMode} onChange={toggleBulkMode} />
						<span className='custom-circle' aria-hidden='true'>
							<svg viewBox='0 0 24 24' aria-hidden='true'>
								<path d='M5 12.5l4 4L19 7.5'></path>
							</svg>
						</span>
						<span className='chk-text'>
							{__('Bulk Select', 'easy-dropbox-integration')}{' '}
							{bulkMode && `(${selectedCards.length})`}
						</span>
					</label>
				</div>
				<div className='edbi-navbar-bottom-right'>
					{/** New Folder */}
					{
						props.showMoreMenu.showNewFolder && (
							<button
								onClick={() => handleCreateFolder()}
								disabled={activeAccount.length === 0}
								className='edbi-button edbi-button--small'
							>
								<VscNewFolder />
								<span>{__('New Folder', 'easy-dropbox-integration')}</span>
							</button>
						)
					}
					<button
						onClick={() => setShowUploader(true)}
						disabled={activeAccount.length === 0}
						className='edbi-upload-btn'
					>
						<FiUploadCloud className='edbi-upload-icon' />
						<span>{__('Upload', 'easy-dropbox-integration')}</span>
					</button>

					<button
						disabled={isLoading}
						onClick={() => {
							setRefresh((prev) => !prev);
							setIsLoading(true);
						}}
						className='edbi-button edbi-button--small'
					>
						<FiRefreshCw
							className={`edbi-upload-icon ${
								isLoading ? 'edbi-rotate-animation' : ''
							} `}
						/>
						<span>{__('Refresh', 'easy-dropbox-integration')}</span>
					</button>

					<div className='view-btns-container'>
						<button onClick={() => setGridView(true)} className='view-btn'>
							<TbLayoutGrid
								className={`edbi-view-btn-icon ${gridView === true ? 'view' : ''}`}
							/>
						</button>
						<button onClick={() => setGridView(false)} className='view-btn'>
							<TbListDetails
								className={`edbi-view-btn-icon ${gridView !== true ? 'view' : ''}`}
							/>
						</button>
					</div>
					{selectedCards.length === 1 && (
						<VscInfo onClick={() => setShowDetails(true)} className='edbi-info-icon' />
					)}
					{selectedCards.length > 0 && (
						<div onClick={toggleDropdownAction} ref={actionButtonRef}>
							<TbDotsVertical
								className={`edbi-dot-icon edbi-nav-dot ${
									!dropdownAction && 'edbi-dot-animation'
								}`}
							/>

							{dropdownAction && <MultipleItemAction actionRef={actionRef} />}
						</div>
					)}
				</div>
			</section>
		</nav>
	);
};

export default Navbar;
