import { useContext, useEffect, useState } from '@wordpress/element';

import { FaDropbox, FaFolderOpen } from 'react-icons/fa';
import { MdOutlineKeyboardArrowRight, MdOutlinePhotoSizeSelectActual } from 'react-icons/md';
import Parcentage from './Parcentage';
import { decode } from 'js-base64';
import { ThemeContext } from '../Provider/Context';
import { HiOutlineChevronLeft } from 'react-icons/hi';
import { __ } from '@wordpress/i18n';
const Sidebar = () => {
	const [isFile, setIsFile] = useState(true);
	const [isParentOpen, setIsParentOpen] = useState(true);
	const [openChild, setOpenChild] = useState(null);

	const { folders, showContexify, setPath, currentPath, isLoading, setHideSidebar, hideSidebar } =
		useContext(ThemeContext);

	const [allFolders, setAllFolders] = useState([]);

	const pathParts = currentPath.split('/').filter(Boolean);

	useEffect(() => {
		setAllFolders(folders);
	}, [folders]);

	const currentFolder = `${currentPath.split('/')[currentPath.split('/').length - 1]}`;
	const previousFolder = folders.filter((fold) => fold.path.split('/').includes(currentFolder));

	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 handleChildClick = (name) => {
		setOpenChild(openChild === name ? null : name);
	};

	return (
		<>
			{!hideSidebar && (
				<aside className='edbi-sidebar'>
					<div className='edbi-sidebar-header'>
						<img
							src={`${EDBIData?.assets}/images/edbi.png`}
							alt={__('UltraDevs Logo', 'easy-dropbox-integration')}
							className='edbi-logo'
						/>
						<div className='edbi-sidebar-closer'>
							<button onClick={() => setHideSidebar(true)}>
								<HiOutlineChevronLeft />
							</button>
						</div>
					</div>
					<div className='edbi-sidebar-nav-container'>
						<section
							onClick={() => setIsFile(true)}
							className={`sidebar-navlink ${
								isFile === true ? 'edbi-active-button' : ''
							}`}
						>
							<FaFolderOpen className='edbi-icon' />{' '}
							{__('All Files', 'easy-dropbox-integration')}
						</section>
						<section
							onClick={() => setIsFile(false)}
							className={`sidebar-navlink ${
								isFile === false ? 'edbi-active-button' : ''
							}`}
						>
							<MdOutlinePhotoSizeSelectActual className='edbi-icon' />{' '}
							{__('Photos', 'easy-dropbox-integration')}
						</section>
					</div>

					{isFile ? (
						<div className='edbi-sidebar-folder-container'>
							<h6>{__('Folders', 'easy-dropbox-integration')}</h6>
							<div className='edbi-folder-container'>
								<div
									className={`edbi-folder-label ${isParentOpen ? 'active' : ''}`}
									onClick={() => setIsParentOpen(!isParentOpen)}
								>
									<MdOutlineKeyboardArrowRight
										className={`edbi-right-arrow ${
											isParentOpen ? 'edbi-rotate' : ''
										}`}
									/>
									<FaDropbox className='edbi-dropbox-icon' />
									<span>{__('My Dropbox', 'easy-dropbox-integration')}</span>
								</div>

								{isParentOpen && (
									<div className='edbi-folder-content'>
										{allFolders.map((folder, idx) => (
											<div key={idx}>
												<div
													key={idx}
													onClick={() => setPath(folder.path)}
													onContextMenu={(e) => {
														if (false === showContexify) {
															return;
														}
														showContexify(e, 'file-browser-folder', {
															type: 'folder',
															path: folder.path,
															item: folder,
														});
													}}
												>
													<div
														className={`edbi-folder-label edbi-child ${
															currentFolder ===
															folder.path.split('/')[1]
																? 'active'
																: ''
														}`}
														onClick={() => handleChildClick(folder)}
													>
														<MdOutlineKeyboardArrowRight
															className={`edbi-right-arrow ${
																currentFolder ===
																folder.path.split('/')[1]
																	? 'edbi-rotate'
																	: ''
															}`}
														/>
														<FaFolderOpen className='edbi-folder-icon' />
														<span className='edbi-sidebar-folder'>
															<span className='edbi-folder-name'>
																{__(
																	folder.name,
																	'easy-dropbox-integration'
																)}
															</span>
														</span>
													</div>
												</div>
												{pathParts.map((part, index) => {
													const pathUpToHere =
														'/' +
														pathParts.slice(0, index + 1).join('/');

													return (
														<div
															className='edbi-folder-subcontent'
															key={index}
														>
															{folder.path === pathUpToHere &&
																!isLoading &&
																folders.map((fold, idx) => {
																	return (
																		<div
																			key={idx}
																			onClick={() =>
																				setPath(fold.path)
																			}
																			className='edbi-folder-item'
																		>
																			<div className='edbi-border-arrow' />
																			<FaFolderOpen className='edbi-folder-icon' />
																			{__(
																				fold.name,
																				'easy-dropbox-integration'
																			)}
																		</div>
																	);
																})}
														</div>
													);
												})}
											</div>
										))}
									</div>
								)}
							</div>

							<Parcentage
								usedGB={activeAccount?.storage?.used}
								totalGB={activeAccount?.storage?.allocated}
							/>
						</div>
					) : (
						<div className='edbi-photos-container'>
							{__('Photos will appear here', 'easy-dropbox-integration')}
						</div>
					)}
				</aside>
			)}
		</>
	);
};

export default Sidebar;
