import { useEffect, useState } from 'react';
import { Product } from './product';
import { fetchPricingLogic } from '../../fetching/fetch-pricing-logic';
import { useBoundStore } from '../../store/store';
import { __ } from '@wordpress/i18n';

let haveProductsBeenFetched = false;

interface PricingRuleProps {}

export function PricingRules(props: PricingRuleProps) {
	const [loading, setLoading] = useState(true);
	const { products, setProducts, addBanner } = useBoundStore((state) => ({
		products: state.getProductsWithPricingLevels(),
		setProducts: state.setProducts,
		addBanner: state.addBanner,
	}));

	useEffect(() => {
		// only fetch data once, regardless of how many times this component
		// is mounted/rendered.
		if (haveProductsBeenFetched) {
			setLoading(false);
			return;
		}

		const getRules = async () => {
			setLoading(true);
			try {
				const fetchedProducts = await fetchPricingLogic();
				setProducts(fetchedProducts);
			} catch (err) {
				addBanner(
					__(
						'Error fetching pricing rules.',
						'gp-conditional-pricing'
					),
					'error'
				);
				// eslint-disable-next-line no-console
				console.error(err);
			} finally {
				setLoading(false);
				haveProductsBeenFetched = true;
			}
		};

		getRules();
	}, [setLoading, setProducts, addBanner]);

	if (loading || products === null) {
		return (
			<div>
				<p>{__('Loading…', 'gp-conditional-pricing')}</p>
			</div>
		);
	}

	if (products.length === 0) {
		return (
			<div className="gwcp-no-pricing-levels gform-settings-panel gform-settings-panel--full">
				<h4>
					{__(
						'You have not added any pricing levels.',
						'gp-conditional-pricing'
					)}
				</h4>
				<p>
					{__(
						'Select a product from the drop down above to add a pricing level for that product.',
						'gp-conditional-pricing'
					)}
				</p>
			</div>
		);
	}

	return (
		<div>
			{products.map((product) => (
				<Product key={`product_${product.id}`} product={product} />
			))}
		</div>
	);
}
