import { useMemo, useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

import NoDataPlaceholder from '../../shared/NoDataPlaceholder';
import Table from '../../shared/Table';

import { decodeHtmlEntities } from './../../shared/utils';

import PageAnalytics from '../../shared/PageAnalytics';

export default function SitePersonalization( props ) {
	const { getCachedData, setCachedData } = props;

	const [ data, setData ] = useState( null );
	const [ error, setError ] = useState( null );

	const [ isModalOpen, setIsModalOpen ] = useState( false );
	const [ modalData, setModalData ] = useState( null );

	const ENDPOINT = '/growthstack/v1/analytics/personalization/';

	useEffect( () => {
		const cached = getCachedData( ENDPOINT );

		if ( cached?.isFetched ) {
			setData( cached.data );
			setError( cached.error );
			return;
		}

		setError( null );

		apiFetch( { path: ENDPOINT } )
			.then( ( response ) => {
				const responseData = response || null;
				setData( responseData );
				setCachedData( ENDPOINT, responseData, null );
			} )
			.catch( ( fetchError ) => {
				setError( fetchError );
				setCachedData( ENDPOINT, null, fetchError );
				// eslint-disable-next-line no-console
				console.error(
					'Failed to fetch personalization data',
					fetchError
				);
			} );
	}, [ getCachedData, setCachedData ] );

	const isLoading = ! data && ! error;

	const refinedData = useMemo( () => {
		if ( !! data && !! data.overview_365 ) {
			return Object.values(
				data?.overview_365 as SitePersonalizationReport[]
			).map( ( page ) => {
				let clicks = 0;
				let views = 0;

				let variations = 0;

				// sum all clicks and views from non-default variations
				page.analytics.forEach( ( variation ) => {
					if ( variation.is_default ) {
						return; // skip default variations
					}
					variations++;
					clicks += variation.clicks || 0;
					views += variation.views || 0;
				} );

				return {
					title: decodeHtmlEntities( page.title ),
					url: page.url,
					count: page.personalization_count,
					modal: page.modal,
					clicks,
					views,
					variationCount: variations,
				};
			} );
		}
		return [];
	}, [ data ] );

	// sort by viewCount
	const sortedData = refinedData;

	return (
		<div
			className={ `gs-box gs-box--headerless ${
				isLoading ? 'is-skeleton' : ''
			}` }
		>
			{ error && (
				<div className="gs-analytics-overview__error">
					{ __(
						"There's an error fetching the data.",
						'liana-with-growthstack'
					) }
				</div>
			) }
			{ !! sortedData && sortedData.length > 0 && (
				<>
					<Table
						className="gs-analytics-overview__ab-testing"
						columns={ [
							{
								Header: __( 'Title', 'liana-with-growthstack' ),
								accessor: 'title',
								Cell: ( { row } ) => (
									<button
										className="gs-analytics-overview__page-link"
										onClick={ () => {
											setModalData( row.original.modal );
											setIsModalOpen( true );
										} }
									>
										{ row.original.title }
									</button>
								),
							},
							{
								Header: __( 'Variations', 'liana-with-growthstack' ),
								accessor: 'variationCount',
								width: 80,
								minWidth: 80,
								maxWidth: 80,
							},
							{
								Header: __( 'Views', 'liana-with-growthstack' ),
								accessor: 'views',
								width: 80,
								minWidth: 80,
								maxWidth: 80,
							},
							{
								Header: __( 'Clicks', 'liana-with-growthstack' ),
								accessor: 'clicks',
								width: 80,
								minWidth: 80,
								maxWidth: 80,
							},
						] }
						data={ sortedData }
					/>
					{ isModalOpen && (
						<PageAnalytics
							isOpen={ isModalOpen }
							onClose={ () => setIsModalOpen( false ) }
							data={ modalData }
						/>
					) }
				</>
			) }
			{ !! sortedData && sortedData.length === 0 && ! isLoading && (
				<NoDataPlaceholder type="personalization">
					<p>
						{ __( 'No personalizations running.', 'liana-with-growthstack' ) }
					</p>
					<p>
						{ __(
							'Add personalizations to your site to see data here.',
							'liana-with-growthstack'
						) }
					</p>
				</NoDataPlaceholder>
			) }
		</div>
	);
}
