import React, { useState, useCallback, useRef, useEffect } from '@wordpress/element';
import classNames from 'classnames';
import Gallery from 'react-photo-gallery';
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 { FaFolderOpen } from 'react-icons/fa';
import { formatBytes, generateFileItem, filterItems } from '../../utils/common';

const ImageGallery = ({ data, accountId }) => {
	const [galleryItems, setGalleryItems] = useState([]);
	const [colWidth, setColWidth] = useState(0);
	const lightGallery = useRef(null);

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

	console.log('data', data);

	// Get filter settings from shortcode data
	const filters = data?.settings?.filters || {};
	const showFolders = filters?.showFolders ?? false;

	// Get all items (files) and apply filters
	const allItems = data?.source?.items?.files || [];
	const filteredItems = filterItems(allItems, filters, true);

	const items = filteredItems;

	// Get folders if showFolders is enabled
	const allFolders = data?.source?.items?.folders || [];
	const filteredFolders = showFolders ? filterItems(allFolders, filters, false) : [];

	const photos = items.map((item) => ({
		src: item.thumbnail,
		width: item?.metadata?.width || 4,
		height: item?.metadata?.height || 3,
		alt: item.name,
		size: formatBytes(item.size),
	}));

	useEffect(() => {
		const lgItems = items.map((file) => generateFileItem(file));
		setGalleryItems(lgItems);
	}, [items]);

	const columnsConfig = data?.settings?.gallery?.columns;
	const margin = data?.settings?.gallery?.margin || 5;
	const layout = data?.settings?.gallery?.layout;
	const thumbnailView = data?.settings?.gallery?.thumbnailView;

	const getColumns = () => {
		const width = window.innerWidth;
		if (width < 768) {
			return columnsConfig?.mobile || 1;
		} else if (width < 992) {
			return columnsConfig?.tablet || 2;
		} else if (width < 1200) {
			return columnsConfig?.laptop || 3;
		} else if (width < 1600) {
			return columnsConfig?.desktop || 4;
		} else {
			return columnsConfig?.largeDesktop || 5;
		}
	};

	useEffect(() => {
		setColWidth(getColumns());

		const handleResize = () => {
			setColWidth(getColumns());
		};

		window.addEventListener('resize', handleResize);
		return () => window.removeEventListener('resize', handleResize);
	}, [data]);

	// Calculate column width for CSS Grid or Flexbox
	const getColumnWidth = `calc(${100 / colWidth}% - ${2 * margin}px)`;

	// Folder colors for visual variety (matching file browser)
	const pastelColors = [
		'#2772f0cc',
		'#ffa000',
		'#f98db4',
		'#7b6fff',
		'#27d3a2',
		'#8c42ac',
		'#2fb776cc',
		'#58d9fd',
		'#f05d27',
		'#bbd622',
	];

	return (
		<div
			className={classNames(
				'edbi-gallery',
				`edbi-gallery--${layout}`,
				`edbi-gallery--style-${thumbnailView}`
			)}
			style={{
				'--column-width': getColumnWidth || 'calc(100%-5px)',
				'--aspect-ratio': data?.settings?.gallery?.aspectRatio
					? data?.settings?.gallery?.aspectRatio.replace(':', ' / ')
					: 1,
			}}
		>
			{/* Folders Section - File Browser Style */}
			{showFolders && filteredFolders.length > 0 && 1 !== 1 && (
				<div className={classNames('edbi-folder-grid-container', `edbi-grid-${colWidth}`)}>
					{filteredFolders.map((folder, index) => (
						<div
							key={`folder-${folder.id || index}`}
							className='edbi-folder-container'
							onClick={() => {
								console.log('Navigate to folder:', folder.path, folder.name);
							}}
						>
							{/* Shadow effect */}
							<div
								className='edbi-shadow'
								style={{
									background: `radial-gradient(circle, ${
										pastelColors[index % pastelColors.length]
									} 0%, transparent 100%)`,
								}}
							/>

							<div className='edbi-folder'>
								<div className='edbi-name-folder'>
									<FaFolderOpen
										className='edbi-folder-icon'
										style={{
											color: pastelColors[index % pastelColors.length],
										}}
									/>
									<span>{folder.name}</span>
								</div>
							</div>
						</div>
					))}
				</div>
			)}

			{/* Files Section - Gallery Style */}
			<Gallery
				photos={photos}
				columns={colWidth}
				margin={parseInt(margin)}
				onClick={(e, object) => {
					lightGallery.current.openGallery(object.index);
				}}
				renderImage={({ index, onClick, photo, margin, direction, top, left }) => {
					const { src, alt } = photo;
					const imgStyle = {
						display: 'block',
						margin: `${margin}px`,
					};

					const handleClick = (event) => {
						onClick(event, { photo, index });
					};

					if (direction === 'column') {
						imgStyle.position = 'absolute';
						imgStyle.left = left;
						imgStyle.top = top;
					}

					return (
						<div
							className='edbi-gallery__item'
							style={imgStyle}
							onClick={onClick ? handleClick : null}
						>
							<img src={src} alt={alt} style={{ width: '100%', height: '100%' }} />
							{data?.settings?.gallery?.overlay && (
								<div
									className={classNames(
										'edbi-gallery__item__overlay',
										`edbi-gallery__item__overlay--${data?.settings?.gallery?.overlayDisplay}`
									)}
								>
									{data?.settings?.gallery?.showTitle && <h3>{photo?.alt}</h3>}
									{data?.settings?.gallery?.showSize && <h4>{photo?.size}</h4>}
								</div>
							)}
						</div>
					);
				}}
			/>
			<LightGallery
				onInit={onInit}
				elementClassNames={'gallery'}
				dynamic={true}
				plugins={[lgZoom, lgVideo, lgThumbnail, lgAutoplay, lgFullscreen]}
				licenseKey='DEC07C11-66CA-441B-91EB-78600E170147'
				dynamicEl={galleryItems}
			></LightGallery>
		</div>
	);
};

export default ImageGallery;
