import { __ } from '@wordpress/i18n';
import { createPortal } from 'react-dom';
import { useState } from '@wordpress/element';

import SitePopularPages from '../components/SitePopularPages';
import SiteAnalyticsOverview from '../components/SiteAnalyticsOverview';
import SiteAudience from '../components/SiteAudience';
import Tabs from '../../shared/Tabs';
import Tab from '../../shared/Tab';

const SiteAnalytics = ( props ) => {
	const { assetsFolder, isLianaAutomationActive, lianaAdminPageUrl, upgradeUrl } = props;

	const [ dataCache, setDataCache ] = useState( {} );

	const getCachedData = ( endpoint ) => {
		return dataCache[ endpoint ] || null;
	};

	const setCachedData = ( endpoint, data, error = null ) => {
		setDataCache( ( prevCache ) => ( {
			...prevCache,
			[ endpoint ]: { data, error, isFetched: true },
		} ) );
	};

	const tabHeadersTarget =
		typeof window !== 'undefined'
			? document.querySelector( '.js-growthstack-view-tabs' )
			: null;

	return (
		<Tabs
			urlKey="tab"
			renderTabHeaders={ ( headers ) =>
				tabHeadersTarget
					? createPortal( headers, tabHeadersTarget )
					: null
			}
			renderTabContent={ ( content ) => content }
		>
			<Tab
				label={ __( 'Site Analytics', 'liana-with-growthstack' ) }
				slug="overview"
			>
				<div className="growthstack-analytics-site__overview">
					<SiteAnalyticsOverview
						getCachedData={ getCachedData }
						setCachedData={ setCachedData }
					/>
				</div>
			</Tab>
			<Tab
				label={ __( 'Most Popular', 'liana-with-growthstack' ) }
				slug="most-popular-pages"
			>
				<SitePopularPages
					getCachedData={ getCachedData }
					setCachedData={ setCachedData }
					assetsFolder={ assetsFolder }
				/>
			</Tab>
			<Tab label={ __( 'Audience', 'liana-with-growthstack' ) } slug="audience" isPro={ true }>
				<SiteAudience
					getCachedData={ getCachedData }
					setCachedData={ setCachedData }
					assetsFolder={ assetsFolder }
					isLianaAutomationActive={ isLianaAutomationActive }
					lianaAdminPageUrl={ lianaAdminPageUrl }
					upgradeUrl={ upgradeUrl }
				/>
			</Tab>
		</Tabs>
	);
};

export default SiteAnalytics;
