import { __ } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import { updateBadge } from '../../../../../../features/discount/discountSlice';
import productBadgeDesign from '../../../../../../utilities/product-badge-design';

const BadgeItems = ({ selectedBadge, className }) => {
	const dispatch = useDispatch();
	const { badge } = useSelector((state) => state.discount.design_blocks);
	const isSelectedDesign = badge?.selected_design || null;

	const handleDesignSelect = (designKey) => {
		const selectedDesign = productBadgeDesign[selectedBadge].find(
			(design) => design.id === designKey
		);
		if (!selectedDesign) return;

		// Update selected design key
		dispatch(updateBadge({ name: 'selected_design', value: designKey }));
		// Update badge type
		dispatch(updateBadge({ name: 'badge_type', value: selectedBadge }));

		// Apply title styles (keep existing text)
		dispatch(
			updateBadge({
				name: 'title',
				value: selectedDesign.title,
			})
		);

		// Apply container styles
		dispatch(
			updateBadge({
				name: 'container',
				value: selectedDesign.container,
			})
		);

		// Apply image URL
		if (selectedBadge === 'value_editable') {
			dispatch(
				updateBadge({
					name: 'design',
					value: selectedDesign.design,
				})
			);
		}
	};

	return (
		<>
			<div
				className={`disco-max-h-[300px] disco-overflow-y-auto disco-overscroll-contain disco-rounded-lg disco-bg-white disco-my-4 disco-py-4 disco-px-4 disco-border-1 disco-no-scrollbar ${className}`}
			>
				<div className="disco-grid disco-grid-cols-4 disco-gap-4 ">
					{productBadgeDesign?.[selectedBadge] ? (
						Object.values(productBadgeDesign[selectedBadge]).map(
							(badge, index) => (
								<div
									key={index}
									onClick={() =>
										handleDesignSelect(badge?.id)
									}
									className={`disco-flex disco-flex-col disco-border disco-rounded-md disco-p-3 disco-items-center disco-justify-center ${badge.id === isSelectedDesign && 'disco-border-primary'}`}
								>
									<img
										src={badge?.image?.url}
										alt={`Badge ${index + 1}`}
										className="disco-object-contain"
									/>
								</div>
							)
						)
					) : (
						<p className="disco-text-gray-500 disco-text-sm disco-col-span-4 disco-text-center">
							{__(
								'No badges available for the selected option.',
								'disco'
							)}
						</p>
					)}
				</div>
			</div>
		</>
	);
};

export default BadgeItems;
