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

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

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

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

export default function SiteTopPerforming( 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( () => {
		const variants: {
			title: string;
			postType: string;
			name: string;
			url: string;
			count: number;
			modal: any;
			rule: string;
			clicks: number;
			views: number;
		}[] = [];
		if ( !! data && !! data.overview_365 ) {
			for ( const page of Object.values(
				data?.overview_365 as SitePersonalizationReport[]
			) ) {
				if ( ! page.analytics || page.analytics.length === 0 ) {
					continue; // skip pages with no analytics
				}
				// console.log('page', page);
				page.analytics.forEach( ( variation ) => {
					if ( variation.is_default ) {
						return; // skip default variations
					}
					variants.push( {
						title: decodeHtmlEntities( page.title ),
						postType: decodeHtmlEntities( page.type ),
						name: variation.name,
						url: page.url,
						count: page.personalization_count,
						rule: decodeHtmlEntities( variation.rule ),
						modal: page.modal,
						clicks: variation.clicks || 0,
						views: variation.views || 0,
					} );
				} );
			}
			// const sortedByClicks = variants.sort((a, b) => b.clicks - a.clicks);
			// const sortedByViews = sortedByClicks.sort((a, b) => b.views - a.views);

			// const topVariants = sortedByViews.slice(0, 10); // get top 10 variants

			return variants;
		}
		return [];
	}, [ data ] );

	const topByClicks = useMemo( () => {
		// remove items with 0 clicks
		const filteredData = refinedData.filter( ( item ) => item.clicks > 0 );
		return filteredData
			.sort( ( a, b ) => b.clicks - a.clicks )
			.slice( 0, 10 );
	}, [ refinedData ] );
	const topByViews = useMemo( () => {
		// remove items with 0 views
		const filteredData = refinedData.filter( ( item ) => item.views > 0 );
		return filteredData
			.sort( ( a, b ) => b.views - a.views )
			.slice( 0, 10 );
	}, [ refinedData ] );

	return (
		<div className="growthstack-top-personalizations">
			<div className={ `gs-box ${ isLoading ? 'is-skeleton' : '' }` }>
				<h2 className="gs-box__title">
					{ __( 'Most Viewed', 'liana-with-growthstack' ) }
				</h2>
				{ isLoading && <Spinner /> }
				{ error && (
					<div className="gs-analytics-overview__error">
						{ __(
							"There's an error fetching the data.",
							'liana-with-growthstack'
						) }
					</div>
				) }
				{ !! topByViews && topByViews.length > 0 && (
					<>
						<Table
							className="gs-analytics-overview__ab-testing"
							columns={ [
								{
									Header: __( 'Variation', 'liana-with-growthstack' ),
									accessor: 'name',
									Cell: ( { row } ) => (
										<button
											className="gs-variant-button"
											onClick={ () => {
												setModalData(
													row.original.modal
												);
												setIsModalOpen( true );
											} }
										>
											<span className="gs-variant-button__name">
												{ row.original.name }
											</span>
											{ row.original.rule && (
												<span className="gs-variant-button__type">
													{ row.original.rule }
												</span>
											) }
										</button>
									),
								},
								{
									Header: __( 'Page', 'liana-with-growthstack' ),
									accessor: 'title',
									Cell: ( { row } ) => (
										<button
											className="gs-variant-button"
											onClick={ () => {
												setModalData(
													row.original.modal
												);
												setIsModalOpen( true );
											} }
										>
											<span className="gs-variant-button__name">
												{ row.original.title }
											</span>
											{ /* {row.original.postType && (
												<span className="gs-variant-button__type">{row.original.postType}</span>
											)} */ }
										</button>
									),
								},
								{
									Header: __( 'Views', 'liana-with-growthstack' ),
									accessor: 'views',
									width: 80,
									minWidth: 80,
									maxWidth: 80,
								},
							] }
							data={ topByViews }
						/>
					</>
				) }
				{ !! topByViews && topByViews.length === 0 && ! isLoading && (
					<NoDataPlaceholder type="personalization">
						<p>
							{ __(
								"There's no data to show yet.",
								'liana-with-growthstack'
							) }
						</p>
					</NoDataPlaceholder>
				) }
			</div>

			<div className={ `gs-box ${ isLoading ? 'is-skeleton' : '' }` }>
				<h2 className="gs-box__title">
					{ __( 'Most Clicked', 'liana-with-growthstack' ) }
				</h2>
				{ isLoading && <Spinner /> }
				{ error && (
					<div className="gs-analytics-overview__error">
						{ __(
							"There's an error fetching the data.",
							'liana-with-growthstack'
						) }
					</div>
				) }
				{ !! topByClicks && topByClicks.length > 0 && (
					<>
						<Table
							className="gs-analytics-overview__ab-testing"
							columns={ [
								{
									Header: __( 'Variation', 'liana-with-growthstack' ),
									accessor: 'name',
									Cell: ( { row } ) => (
										<button
											className="gs-variant-button"
											onClick={ () => {
												setModalData(
													row.original.modal
												);
												setIsModalOpen( true );
											} }
										>
											<span className="gs-variant-button__name">
												{ row.original.name }
											</span>
											{ row.original.rule && (
												<span className="gs-variant-button__type">
													{ row.original.rule }
												</span>
											) }
										</button>
									),
								},
								{
									Header: __( 'Page', 'liana-with-growthstack' ),
									accessor: 'title',
									Cell: ( { row } ) => (
										<button
											className="gs-variant-button"
											onClick={ () => {
												setModalData(
													row.original.modal
												);
												setIsModalOpen( true );
											} }
										>
											<span className="gs-variant-button__name">
												{ row.original.title }
											</span>
											{ /* {row.original.postType && (
												<span className="gs-variant-button__type">{row.original.postType}</span>
											)} */ }
										</button>
									),
								},
								{
									Header: __( 'Clicks', 'liana-with-growthstack' ),
									accessor: 'clicks',
									width: 80,
									minWidth: 80,
									maxWidth: 80,
								},
							] }
							data={ topByClicks }
						/>
					</>
				) }
				{ !! topByClicks && topByClicks.length === 0 && ! isLoading && (
					<NoDataPlaceholder type="personalization">
						<p>
							{ __(
								"There's no data to show yet.",
								'liana-with-growthstack'
							) }
						</p>
					</NoDataPlaceholder>
				) }
			</div>
			{ isModalOpen && (
				<PageAnalytics
					isOpen={ isModalOpen }
					onClose={ () => setIsModalOpen( false ) }
					data={ modalData }
				/>
			) }
		</div>
	);
}
