import { __ } from '@wordpress/i18n';
import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { Button } from '@wordpress/components';

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

const getAnalyticsAbTestsAPI = () => {
	if ( typeof window === 'undefined' ) {
		return {} as Record< string, any >;
	}
	const growthstack = ( window as any ).growthstack ?? {};
	return growthstack.analyticsAbTests ?? {};
};

const formatTrendValue = ( value: number, format: string ) => {
	if ( format === 'compact' ) {
		if ( value >= 1000000 ) {
			return `${ ( value / 1000000 ).toFixed( 1 ) }M`;
		}
		if ( value >= 1000 ) {
			return `${ ( value / 1000 ).toFixed( 1 ) }k`;
		}
	}
	return value.toString();
};

const formatString = ( template: string, ...args: any[] ) => {
	let i = 0;
	return template.replace( /%s/g, () => args[ i++ ] );
};

const formatDate = ( publishedAt: string ) => {
	if ( ! publishedAt ) {
		return __( 'Draft', 'liana-with-growthstack' );
	}
	const date = new Date( publishedAt );
	const formattedDate = date.toLocaleDateString( 'fi-FI', {
		year: 'numeric',
		month: 'numeric',
		day: 'numeric',
	} );
	return formatString( __( 'Since %s', 'liana-with-growthstack' ), formattedDate );
};

const getPlaceholderData = () => [
	{
		title: 'Ultimate Guide to Web Performance',
		type: 'post',
		days: 14,
		publishedAt: new Date( Date.now() - 14 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 3420,
		conversionsA: 145,
		conversionsB: 178,
	},
	{
		title: 'Getting Started with A/B Testing',
		type: 'post',
		days: 7,
		publishedAt: new Date( Date.now() - 7 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 1850,
		conversionsA: 92,
		conversionsB: 87,
	},
	{
		title: 'Product Features Overview',
		type: 'page',
		days: 21,
		publishedAt: new Date( Date.now() - 21 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 5230,
		conversionsA: 234,
		conversionsB: 289,
	},
	{
		title: 'Contact Us - Get in Touch',
		type: 'page',
		days: 3,
		publishedAt: new Date( Date.now() - 3 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 890,
		conversionsA: 45,
		conversionsB: 52,
	},
	{
		title: 'Best Practices for 2026',
		type: 'post',
		days: 10,
		publishedAt: new Date( Date.now() - 10 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 2100,
		conversionsA: 118,
		conversionsB: 105,
	},
	{
		title: 'How to Optimize Your Landing Pages',
		type: 'page',
		days: 5,
		publishedAt: new Date( Date.now() - 5 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 1420,
		conversionsA: 68,
		conversionsB: 74,
	},
	{
		title: 'Advanced Marketing Strategies',
		type: 'post',
		days: 28,
		publishedAt: new Date( Date.now() - 28 * 24 * 60 * 60 * 1000 ).toISOString(),
		views: 4780,
		conversionsA: 198,
		conversionsB: 215,
	},
];

const DefaultABTestsContent = ( props: { upgradeUrl?: string } ) => {
	const placeholderData = getPlaceholderData();

	return (
		<>
			<div className="gs-header-box">
				<div className="gs-header-box__main">
					<h2>{ __( 'A/B Tests', 'liana-with-growthstack' ) }</h2>
					<p>
						{ __(
							'Active A/B Tests from all posts and pages.',
							'liana-with-growthstack'
						) }
					</p>
				</div>
			</div>
			<div className="gs-box gs-box--headerless growthstack-ab__placeholder-table">
				<Table
					className="gs-analytics-overview__ab-testing"
					columns={ [
						{
							Header: __( 'Title', 'liana-with-growthstack' ),
							accessor: 'title',
							width: 250,
							minWidth: 100,
							maxWidth: 250,
							Cell: ( { row } ) => (
								<div className="gs-page-modal-button gs-page-modal-button--disabled">
									<span className="gs-page-modal-button__name">
										{ row.original.title }
									</span>
									<span className="gs-page-modal-button__type">
										{ row.original.type }
									</span>
								</div>
							),
						},
						{
							Header: __( 'Running', 'liana-with-growthstack' ),
							accessor: 'days',
							width: 120,
							minWidth: 100,
							maxWidth: 120,
							Cell: ( { row } ) => (
								<div className="growthstack-ab__running">
									<span className="growthstack-ab__running-days">
										{ row.original.days === 1
											? formatString(
													__(
														'%s day',
														'liana-with-growthstack'
													),
													row.original.days
											)
											: formatString(
													__(
														'%s days',
														'liana-with-growthstack'
													),
													row.original.days
											) }
									</span>
									<span className="growthstack-ab__running-published">
										{ formatDate(
											row.original.publishedAt
										) }
									</span>
								</div>
							),
						},
						{
							Header: __(
								'Conversion Distribution',
								'liana-with-growthstack'
							),
							accessor: 'conversionsA',
							width: 140,
							minWidth: 130,
							maxWidth: 140,
							Cell: ( { row } ) => (
								<ABConversionBar
									conversionsA={ row.original.conversionsA }
									conversionsB={ row.original.conversionsB }
								/>
							),
						},
						{
							Header: __( 'Views', 'liana-with-growthstack' ),
							accessor: 'views',
							width: 90,
							minWidth: 80,
							maxWidth: 100,
							Cell: ( { row } ) => (
								<span className="gs-analytics-overview__views">
									{ formatTrendValue(
										row.original.views,
										'compact'
									) }
								</span>
							),
						},
						{
							Header: ' ',
							Cell: ( { row } ) => (
								<Button
									className="growthstack-ab__complete"
									variant="secondary"
									disabled
								>
									<span>
										{ __(
											'Complete test',
											'liana-with-growthstack'
										) }
									</span>
									<svg
										width="15"
										height="16"
										viewBox="0 0 15 16"
										fill="none"
										xmlns="http://www.w3.org/2000/svg"
									>
										<rect
											width="14"
											height="14"
											transform="translate(0.5 1.01147)"
											fill="black"
											fillOpacity="0.01"
										/>
										<path
											d="M8.8125 1.41772C8.8125 1.06226 9.08594 0.761475 9.46875 0.761475H13.8164C14.1992 0.761475 14.4727 1.06226 14.4727 1.41772V5.79272C14.4727 6.17554 14.1992 6.44897 13.8164 6.44897C13.4609 6.44897 13.1602 6.17554 13.1602 5.79272V3.00366L7.0625 9.10132C6.81641 9.37476 6.40625 9.37476 6.16016 9.10132C5.88672 8.85522 5.88672 8.44507 6.16016 8.17163L12.2578 2.07397H9.46875C9.08594 2.07397 8.8125 1.80054 8.8125 1.41772ZM2.46875 1.63647H5.96875C6.32422 1.63647 6.625 1.93726 6.625 2.29272C6.625 2.67554 6.32422 2.94897 5.96875 2.94897H2.46875C2.08594 2.94897 1.8125 3.24976 1.8125 3.60522V12.7927C1.8125 13.1755 2.08594 13.449 2.46875 13.449H11.6562C12.0117 13.449 12.3125 13.1755 12.3125 12.7927V9.29272C12.3125 8.93726 12.5859 8.63647 12.9688 8.63647C13.3242 8.63647 13.625 8.93726 13.625 9.29272V12.7927C13.625 13.8865 12.7227 14.7615 11.6562 14.7615H2.46875C1.375 14.7615 0.5 13.8865 0.5 12.7927V3.60522C0.5 2.53882 1.375 1.63647 2.46875 1.63647Z"
											fill="#353A40"
										/>
									</svg>
								</Button>
							),
						},
					] }
					data={ placeholderData }
				/>
				<div className="growthstack-ab__placeholder-overlay">
					<div className="growthstack-ab__placeholder-message">
						<div className="growthstack-ab__placeholder-message__inner">
							<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 25 28" width="20" height="20"><path fill="#353a40" d="M7.875 7v3.5h8.75V7a4.39 4.39 0 0 0-4.375-4.375A4.353 4.353 0 0 0 7.875 7M5.25 10.5V7c0-3.828 3.117-7 7-7 3.828 0 7 3.172 7 7v3.5H21c1.914 0 3.5 1.586 3.5 3.5v10.5A3.49 3.49 0 0 1 21 28H3.5C1.531 28 0 26.469 0 24.5V14a3.49 3.49 0 0 1 3.5-3.5zM2.625 14v10.5c0 .492.383.875.875.875H21c.438 0 .875-.383.875-.875V14c0-.437-.437-.875-.875-.875H3.5c-.492 0-.875.438-.875.875"></path></svg>
							<p><strong>{ __( 'Available for Pro version', 'liana-with-growthstack' ) }</strong></p>
							<p>
								{ __(
									'Get Liana with GrowthStack Pro to run experiments and compare results between variants. A/B Testing is a powerful way to optimize your content and boost conversions across your site.',
									'liana-with-growthstack'
								) }
							</p>
							{ props.upgradeUrl && (
								<a
									href={ props.upgradeUrl }
									target="_blank"
									className='gs-upgrade-button'
								>
									{ __( 'Upgrade to Pro', 'liana-with-growthstack' ) }
								</a>
							) }
						</div>
					</div>
				</div>
			</div>
		</>
	);
};

export default function ABTests( props ) {
	const { assetsFolder, upgradeUrl } = props;
	const [ dataCache, setDataCache ] = useState( {} );
	const [ registryVersion, setRegistryVersion ] = useState( 0 );

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

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

	useEffect( () => {
		let unsubscribe: () => void = () => {};
		let pollHandle: number | null = null;
		let isSubscribed = false;

		const attemptSubscribe = () => {
			const { subscribeABTestsScreens } = getAnalyticsAbTestsAPI();
			if ( typeof subscribeABTestsScreens === 'function' ) {
				unsubscribe = subscribeABTestsScreens( () => {
					setRegistryVersion( ( current ) => current + 1 );
				} );
				setRegistryVersion( ( current ) => current + 1 );
				isSubscribed = true;
				return true;
			}
			return false;
		};

		if ( attemptSubscribe() === false && typeof window !== 'undefined' ) {
			pollHandle = window.setInterval( () => {
				if ( attemptSubscribe() && pollHandle !== null ) {
					window.clearInterval( pollHandle );
					pollHandle = null;
				}
			}, 250 );
		}

		return () => {
			if ( pollHandle !== null && typeof window !== 'undefined' ) {
				window.clearInterval( pollHandle );
			}
			if ( isSubscribed && typeof unsubscribe === 'function' ) {
				unsubscribe();
			}
		};
	}, [] );

	const fillProps = useMemo(
		() => ( {
			assetsFolder,
			getCachedData,
			setCachedData,
		} ),
		[ assetsFolder, getCachedData, setCachedData ]
	);

	const registeredScreens = useMemo( () => {
		const { getRegisteredABTestsScreens } = getAnalyticsAbTestsAPI();
		if ( typeof getRegisteredABTestsScreens === 'function' ) {
			return getRegisteredABTestsScreens().filter(
				( FillComponent: any ) => typeof FillComponent === 'function'
			);
		}
		return [];
	}, [ registryVersion ] );
	const hasCustomScreen = registeredScreens.length > 0;
	const { ABTestsSlot: SlotComponent } = getAnalyticsAbTestsAPI();
	const canRenderSlot =
		hasCustomScreen && typeof SlotComponent === 'function';

	return (
		<>
			{ registeredScreens.map( ( FillComponent, index ) => (
				<FillComponent key={ index } />
			) ) }
			{ canRenderSlot ? (
				<SlotComponent fillProps={ fillProps } />
			) : (
				<DefaultABTestsContent upgradeUrl={ upgradeUrl } />
			) }
		</>
	);
}
