/**
 * WordPress dependencies
 */
import { Dashicon, Tooltip } from '@safe-wordpress/components';
import { useSelect } from '@safe-wordpress/data';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { filter, toPairs } from 'lodash';
import { store as NC_DATA, usePost } from '@nelio-content/data';
import { getSupportedNetworks } from '@nelio-content/networks';
import type {
	Maybe,
	Post,
	PostId,
	SocialNetworkName,
} from '@nelio-content/types';

/**
 * Internal dependencies
 */
import './style.scss';
import { SocialNetworkIcon } from '../social-network-icon';

export type PostPageviewsAnalyticsProps = {
	readonly className?: string;
	readonly postId: PostId;
	readonly statistics?: Post[ 'statistics' ];
};

export const PostPageviewsAnalytics = ( {
	className = '',
	postId,
	statistics,
}: PostPageviewsAnalyticsProps ): JSX.Element | null => {
	const isVisible = useIsVisible();
	const pageviews = usePageViews( postId, statistics );
	const metrics = useMetrics( postId, statistics );

	if ( ! isVisible ) {
		return null;
	}

	return (
		<div className={ `nelio-content-pageviews-analytics ${ className }` }>
			<div className="nelio-content-pageviews-analytics__title">
				{ _x( 'Pageviews', 'text', 'nelio-content' ) }
				<Tooltip
					text={ _x(
						'Total pageviews according to Google Analytics',
						'text',
						'nelio-content'
					) }
					placement="bottom"
				>
					<span className="nelio-content-pageviews-analytics__help-icon">
						<Dashicon icon="editor-help" />
					</span>
				</Tooltip>
			</div>

			<div className="nelio-content-pageviews-analytics__value">
				{ pageviews }
			</div>

			<div className="nelio-content-pageviews-analytics__metrics">
				{ metrics.map( ( [ network, metric ] ) => (
					<div
						key={ network }
						className="nelio-content-pageviews-analytics__metric"
					>
						<SocialNetworkIcon
							className="nelio-content-pageviews-analytics__metric-network"
							network={ network }
						/>
						<div className="nelio-content-pageviews-analytics__metric-value">
							{ metric }
						</div>
					</div>
				) ) }
			</div>
		</div>
	);
};

// =====
// HOOKS
// =====

const useIsVisible = () =>
	useSelect( ( select ) => select( NC_DATA ).isGAConnected(), [] );

const usePageViews = ( postId: PostId, statistics?: Post[ 'statistics' ] ) =>
	useSelect(
		( select ) =>
			statistics?.pageviews.total ??
			select( NC_DATA ).getPost( postId )?.statistics.pageviews.total ??
			'–',
		[ postId, statistics ]
	);

const useMetrics = ( postId: PostId, statistics?: Post[ 'statistics' ] ) => {
	const post = usePost( postId );
	const networks = getSupportedNetworks();
	const metrics = statistics?.pageviews || post?.statistics.pageviews || {};
	const pairs = filter(
		toPairs( metrics ),
		< V, >(
			pair: [ 'total' | SocialNetworkName, Maybe< V > ]
		): pair is [ SocialNetworkName, V ] =>
			pair[ 0 ] !== 'total' &&
			pair[ 1 ] !== undefined &&
			pair[ 1 ] !== null // &&
		// parseFloat( pair[ 1 ] as string ) > 0
	);
	return filter( pairs, ( [ network ] ) => networks.includes( network ) );
};
