import { ExternalLink, Modal, TabPanel, Button } from '@wordpress/components';
import { useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

import PageAnalyticsOverview from './PageAnalyticsOverview';
import PageABTesting from './PageABTesting';
import PagePersonalization from './PagePersonalization';
import { decodeHtmlEntities } from './utils';

export default function PageAnalytics( props ) {
	const { buttons, onClose, data } = props;

	const [ dataCache, setDataCache ] = useState( {} );
	const tabListRef = useRef( null );
	const isInitialRenderRef = useRef( true );

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

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

	const [ postId, setPostId ] = useState( data?.postId ?? null );
	const [ postTitle, setPostTitle ] = useState( data?.title ?? null );
	const [ postPermalink, setPostPermalink ] = useState(
		data?.permalink ?? null
	);
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	const [ postStatusLabel, setPostStatusLabel ] = useState(
		data?.statusLabel ?? null
	);
	const [ postDateString, setPostDateString ] = useState(
		data?.date ?? null
	);
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	const [ postIsPublished, setPostIsPublished ] = useState(
		data?.isPublished ?? false
	);
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	const [ endpointPageOverview, setEndpointPageOverview ] = useState(
		data?.endpointPageOverview ?? null
	);
	const [ hasABTests, setHasABTests ] = useState( data?.hasABTests ?? false );
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	const [ hasPersonalizations, setHasPersonalizations ] = useState(
		data?.hasPersonalizations ?? false
	);
	const [ personalizationCount, setPersonalizationCount ] = useState(
		data?.personalizationCount ?? 0
	);
	const [ abTestId, setABTestId ] = useState( data?.abTestId ?? null );
	const [ abTestPublishedAt, setABTestPublishedAt ] = useState(
		data?.abTestPublishedAt ?? null
	);
	const [ supportsABTesting, setSupportsABTesting ] = useState(
		data?.supportsABTesting ?? false
	);
	const [ supportsPersonalization, setSupportsPersonalization ] = useState(
		data?.supportsPersonalization ?? false
	);

	const [ editLink, setEditLink ] = useState( data?.editLink ?? '' );
	const [ activeTab, setActiveTab ] = useState(
		data?.activeTab ?? 'overview'
	);
	const [ isOpen, setOpen ] = useState( props.isOpen ?? false );

	// Update CSS indicator variables when active tab changes
	useEffect( () => {
		if ( ! tabListRef.current || ! isOpen ) {
			return;
		}

		const tabList = tabListRef.current;

		const updateIndicator = () => {
			if ( ! tabList ) {
				return;
			}

			const activeButton = tabList.querySelector( 'button.active-tab' );
			if ( ! activeButton ) {
				return;
			}

			const tabListRect = tabList.getBoundingClientRect();
			const buttonRect = activeButton.getBoundingClientRect();

			// Account for the 32px padding on the tablist
			const paddingLeft = 32;
			const left = buttonRect.left - tabListRect.left + paddingLeft;
			const right = tabListRect.right + buttonRect.right;
			const width = buttonRect.width;

			// Disable transitions for initial render
			if ( isInitialRenderRef.current ) {
				const tabListElement =
					tabList.querySelector( '[role="tablist"]' );
				if ( tabListElement ) {
					tabListElement.setAttribute(
						'data-disable-transition',
						'true'
					);
				}
			}

			tabList.style.setProperty( '--indicator-left', String( left ) );
			tabList.style.setProperty( '--indicator-right', String( right ) );
			tabList.style.setProperty( '--indicator-width', String( width ) );

			// Re-enable transitions after initial render
			if ( isInitialRenderRef.current ) {
				setTimeout( () => {
					requestAnimationFrame( () => {
						const tabListElement =
							tabList.querySelector( '[role="tablist"]' );
						if ( tabListElement ) {
							tabListElement.removeAttribute(
								'data-disable-transition'
							);
						}
						isInitialRenderRef.current = false;
					} );
				}, 100 );
			}
		};

		// Use MutationObserver to detect when active-tab class is applied
		const observer = new MutationObserver( () => {
			updateIndicator();
		} );

		// Observe the tab list for class changes on buttons
		const tabButtons = tabList.querySelectorAll( 'button' );
		tabButtons.forEach( ( button ) => {
			observer.observe( button, {
				attributes: true,
				attributeFilter: [ 'class' ],
			} );
		} );

		// Initial update with multiple attempts to ensure DOM is ready
		updateIndicator();
		const timeoutId1 = setTimeout( updateIndicator, 0 );
		const timeoutId2 = setTimeout( updateIndicator, 50 );
		const timeoutId3 = setTimeout( updateIndicator, 100 );

		// Update on window resize
		window.addEventListener( 'resize', updateIndicator );

		return () => {
			observer.disconnect();
			clearTimeout( timeoutId1 );
			clearTimeout( timeoutId2 );
			clearTimeout( timeoutId3 );
			window.removeEventListener( 'resize', updateIndicator );
		};
	}, [ activeTab, isOpen ] );

	const openModal = () => setOpen( true );
	const closeModal = () => {
		setOpen( false );
		if ( typeof onClose === 'function' ) {
			onClose();
		}
	};

	if ( buttons && buttons.length > 0 ) {
		buttons.forEach( ( growthstackButton ) => {
			growthstackButton.addEventListener( 'click', ( event ) => {
				event.preventDefault();

				const args = JSON.parse( growthstackButton.dataset.args );

				setPostId( args.postId );
				setPostTitle( args.title );
				setPostPermalink( args.permalink );
				setPostStatusLabel( args.statusLabel );
				setPostIsPublished( args.isPublished );
				setPostDateString( args.date );
				setEndpointPageOverview( args.endpointPageOverview );
				setHasABTests( args.hasABTests );
				setPersonalizationCount( args.personalizationCount || 0 );
				setABTestId( args.abTestId );
				setABTestPublishedAt( args.abTestPublishedAt );
				setEditLink( args.editLink );
				setActiveTab( args.activeTab );
				setSupportsABTesting( args.supportsABTesting );
				setSupportsPersonalization( args.supportsPersonalization );
				openModal();
			} );
		} );
	}

	if ( ! postId ) {
		return null;
	}

	const tabs = [
		{
			name: 'overview',
			title: __( 'Page Analytics', 'liana-with-growthstack' ),
			content: (
				<PageAnalyticsOverview
					postId={ postId }
					getCachedData={ getCachedData }
					setCachedData={ setCachedData }
				/>
			),
		},
	];

	if ( supportsPersonalization ) {
		tabs.push( {
			name: 'personalization',
			title: (
				<span>
					{ __( 'Personalization', 'liana-with-growthstack' ) }
					{ personalizationCount > 0 && (
						<span className="gs-tab-count">
							{ personalizationCount }
						</span>
					) }
				</span>
			),
			content: (
				<PagePersonalization
					postId={ postId }
					getCachedData={ getCachedData }
					setCachedData={ setCachedData }
					editLink={ editLink }
					hasABTests={ hasABTests }
				/>
			),
		} );
	}

	if ( supportsABTesting ) {
		tabs.push( {
			name: 'abtest',
			title: (
				<span>
					{ __( 'A/B Tests', 'liana-with-growthstack' ) }
					{ hasABTests && <span className="gs-tab-count">1</span> }
				</span>
			),
			content: (
				<PageABTesting
					getCachedData={ getCachedData }
					setCachedData={ setCachedData }
					postId={ postId }
					hasABTests={ hasABTests }
					abTestId={ abTestId }
					abTestPublishedAt={ abTestPublishedAt }
					hasPersonalizations={ hasPersonalizations }
					editLink={ editLink }
				/>
			),
		} );
	}

	return (
		<>
			{ isOpen && (
				<Modal
					// title={ __( "GrowthStack", "growthstack" ) }
					title={ `${ __(
						'GrowthStack',
						'liana-with-growthstack'
					) }: ${ decodeHtmlEntities( postTitle ) }` }
					onRequestClose={ closeModal }
					style={ {
						width: '100%',
						maxWidth: '1200px',
						maxHeight: 'calc(95% - 32px)',
						height: '100%',
					} }
					className="gs-analytics-modal"
					headerActions={
						<div className="gs-analytics-modal__header-actions">
							{ editLink && (
								<Button
									href={ editLink }
									variant="link"
									className="gs-analytics-modal__header-actions__link gs-analytics-modal__edit-link"
								>
									<svg
										xmlns="http://www.w3.org/2000/svg"
										viewBox="0 0 24 24"
										width="24"
										height="24"
										aria-hidden="true"
										focusable="false"
									>
										<path d="m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z"></path>
									</svg>
									<span>{ __( 'Edit', 'liana-with-growthstack' ) }</span>
								</Button>
							) }
							{ /* { postPermalink && (
							<Button
								href={ postPermalink }
								variant="text"
								className="gs-analytics-modal__header-actions__link gs-analytics-modal__view-link"
							>
								<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z"></path></svg>
								<span>{ __( 'View', 'liana-with-growthstack' ) }</span>
							</Button>
						)} */ }
						</div>
					}
				>
					<div className="gs-analytics-modal__header">
						{ /* <div className="gs-analytics-modal__title">
						<h2>{ postTitle }</h2>
						<span className="gs-analytics-modal__status-label" data-is-published={postIsPublished ? 'true' : 'false'}>{ postStatusLabel }</span>
					</div> */ }
						<div className="gs-analytics-modal__meta">
							<div className="gs-analytics-modal__meta-item">
								<span className="gs-analytics-modal__meta-item__label">
									{ __( 'URL:', 'liana-with-growthstack' ) }
								</span>
								<span className="gs-analytics-modal__meta-item__value">
									<ExternalLink href={ postPermalink }>
										{ postPermalink }
									</ExternalLink>
								</span>
							</div>
							<div className="gs-analytics-modal__meta-item">
								<span className="gs-analytics-modal__meta-item__label">
									{ __( 'Published:', 'liana-with-growthstack' ) }
								</span>
								<span className="gs-analytics-modal__meta-item__value">
									{ postDateString }
								</span>
							</div>
						</div>
					</div>
					<div ref={ tabListRef }>
						<TabPanel
							className="gs-analytics-modal__tabs"
							activeClass="active-tab"
							tabs={ tabs }
							initialTabName={ activeTab }
							onSelect={ ( tabName ) => setActiveTab( tabName ) }
						>
							{ ( tab ) => (
								<div
									data-active-item={ tab.name === activeTab }
								>
									{ tab.content }
								</div>
							) }
						</TabPanel>
					</div>
				</Modal>
			) }
		</>
	);
}
