import { useEffect, useMemo, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { api } from '../api';
import GutenbergBlocks from './GutenbergBlocks';
import ShortcodeBlocks from './ShortcodeBlocks';
import { blockCategorySlugs } from '../components/BlocksListFilters';

/**
 * @param {Array<object>} items
 * @return {Array<{ slug: string, name: string, count: number }>}
 */
function categoryTotalsFromItems( items = [] ) {
	const map = new Map();
	( items || [] ).forEach( ( item ) => {
		blockCategorySlugs( item ).forEach( ( slug ) => {
			const name =
				slug === String( item.categorySlug || '' ).trim()
					? String( item.categoryName || '' ).trim() ||
					  ( slug === 'uncategorized'
							? __( 'Uncategorized', 'joc-blockora-morph' )
							: slug )
					: slug === 'uncategorized'
						? __( 'Uncategorized', 'joc-blockora-morph' )
						: slug;
			if ( ! map.has( slug ) ) {
				map.set( slug, { slug, name, count: 0 } );
			}
			map.get( slug ).count += 1;
		} );
	} );
	return Array.from( map.values() ).sort( ( a, b ) =>
		a.name.localeCompare( b.name, undefined, { sensitivity: 'base' } )
	);
}

/**
 * Unified My Library shell — Blocks / Shortcodes sidenav (mirrors Global Settings).
 *
 * @param {Object}   props
 * @param {Function} props.onNavigate
 * @param {'blocks'|'shortcodes'} props.section
 */
export default function MyLibrary( { onNavigate, section = 'blocks' } ) {
	const isShortcodes = section === 'shortcodes';
	const [ items, setItems ] = useState( [] );
	const [ loadingCats, setLoadingCats ] = useState( true );
	const [ sidebarCategory, setSidebarCategory ] = useState( 'all' );

	useEffect( () => {
		setSidebarCategory( 'all' );
		setLoadingCats( true );
		const path = isShortcodes ? '/user-contents' : '/user-blocks';
		api
			.get( path )
			.then( ( res ) => setItems( res.items || [] ) )
			.catch( () => setItems( [] ) )
			.finally( () => setLoadingCats( false ) );
	}, [ isShortcodes ] );

	const categories = useMemo(
		() => categoryTotalsFromItems( items ),
		[ items ]
	);
	const totalCount = items.length;

	const onLibraryChange = () => {
		const path = isShortcodes ? '/user-contents' : '/user-blocks';
		api
			.get( path )
			.then( ( res ) => setItems( res.items || [] ) )
			.catch( () => {} );
	};

	return (
		<div className="bm-theme-page bm-rise mx-auto flex w-full max-w-[1600px] flex-col px-gutter py-stack-lg font-sans">
			<div className="bm-general-shell">
				<nav
					className="bm-general-nav"
					aria-label={ __( 'My Library sections', 'joc-blockora-morph' ) }
				>
					<button
						type="button"
						className={
							! isShortcodes
								? 'bm-general-nav__item is-active'
								: 'bm-general-nav__item'
						}
						onClick={ () => onNavigate( 'gutenberg-blocks' ) }
					>
						<span
							className="bm-general-nav__icon"
							aria-hidden="true"
						>
							<span className="dashicons dashicons-block-default" />
						</span>
						<span className="bm-general-nav__copy">
							<span className="bm-general-nav__label">
								{ __( 'Blocks', 'joc-blockora-morph' ) }
							</span>
							<span className="bm-general-nav__hint">
								{ __(
									'Gutenberg inserter',
									'joc-blockora-morph'
								) }
							</span>
						</span>
					</button>
					<button
						type="button"
						className={
							isShortcodes
								? 'bm-general-nav__item is-active'
								: 'bm-general-nav__item'
						}
						onClick={ () => onNavigate( 'shortcode-blocks' ) }
					>
						<span
							className="bm-general-nav__icon"
							aria-hidden="true"
						>
							<span className="dashicons dashicons-shortcode" />
						</span>
						<span className="bm-general-nav__copy">
							<span className="bm-general-nav__label">
								{ __( 'Shortcodes', 'joc-blockora-morph' ) }
							</span>
							<span className="bm-general-nav__hint">
								{ __(
									'Paste anywhere',
									'joc-blockora-morph'
								) }
							</span>
						</span>
					</button>

					{ ! loadingCats && totalCount > 0 ? (
						<div className="bm-general-nav__cats">
							<p className="bm-general-nav__cats-label">
								{ __( 'Categories', 'joc-blockora-morph' ) }
							</p>
							<button
								type="button"
								className={
									sidebarCategory === 'all'
										? 'bm-cat-link is-active'
										: 'bm-cat-link'
								}
								onClick={ () => setSidebarCategory( 'all' ) }
							>
								<span className="bm-cat-label">
									{ isShortcodes
										? __(
												'All shortcodes',
												'joc-blockora-morph'
										  )
										: __(
												'All blocks',
												'joc-blockora-morph'
										  ) }
								</span>
								<em className="bm-cat-count">{ totalCount }</em>
							</button>
							{ categories
								.filter( ( cat ) => ( cat.count || 0 ) > 0 )
								.map( ( cat ) => (
								<button
									key={ cat.slug }
									type="button"
									className={
										sidebarCategory === cat.slug
											? 'bm-cat-link is-active'
											: 'bm-cat-link'
									}
									onClick={ () =>
										setSidebarCategory( cat.slug )
									}
								>
									<span className="bm-cat-label">
										{ cat.name }
									</span>
									<em className="bm-cat-count">
										{ cat.count }
									</em>
								</button>
							) ) }
						</div>
					) : null }
				</nav>

				<div className="bm-general-main">
					{ isShortcodes ? (
						<ShortcodeBlocks
							onNavigate={ onNavigate }
							embedded
							sidebarCategory={ sidebarCategory }
							onLibraryChange={ onLibraryChange }
						/>
					) : (
						<GutenbergBlocks
							onNavigate={ onNavigate }
							embedded
							sidebarCategory={ sidebarCategory }
							onLibraryChange={ onLibraryChange }
						/>
					) }
				</div>
			</div>
		</div>
	);
}
