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

import Tabs from './../shared/Tabs';
import Tab from './../shared/Tab';

import SitePersonalization from './components/SitePersonalization';
import SiteRules from './components/SiteRules';
import SiteTopPerforming from './components/SiteTopPerforming';
import AddPersonalization from './components/AddPersonalization';

export default function Personalization( props ) {
	const { assetsFolder } = 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
			renderTabHeaders={ ( headers ) =>
				tabHeadersTarget
					? createPortal( headers, tabHeadersTarget )
					: null
			}
			urlKey="tab"
		>
			<Tab
				label={ __( 'Personalizations', 'liana-with-growthstack' ) }
				slug="overview"
			>
				<div className="gs-header-box">
					<div className="gs-header-box__main">
						<h2>{ __( 'Personalizations', 'liana-with-growthstack' ) }</h2>
						<p>
							{ __(
								'Active personalizations from all posts and pages. Analytics are from past year.',
								'liana-with-growthstack'
							) }
						</p>
					</div>
					<AddPersonalization />
				</div>
				<div className="gs-analytics-personalization">
					<SitePersonalization
						getCachedData={ getCachedData }
						setCachedData={ setCachedData }
						assetsFolder={ assetsFolder }
					/>
					<SiteRules
						getCachedData={ getCachedData }
						setCachedData={ setCachedData }
						assetsFolder={ assetsFolder }
					/>
				</div>
			</Tab>
			<Tab
				label={ __( 'Most Popular', 'liana-with-growthstack' ) }
				slug="most-popular-pages"
			>
				<div className="gs-header-box">
					<div className="gs-header-box__main">
						<h2>{ __( 'Most Popular', 'liana-with-growthstack' ) }</h2>
						<p>
							{ __(
								'Default personalization variants are excluded. Analytics are from past year.',
								'liana-with-growthstack'
							) }
						</p>
					</div>
					<AddPersonalization />
				</div>
				<SiteTopPerforming
					getCachedData={ getCachedData }
					setCachedData={ setCachedData }
					assetsFolder={ assetsFolder }
				/>
			</Tab>
		</Tabs>
	);
}
