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

import AnalysisFilters from '../../shared/AnalysisFilters';
import Analysis from '../../shared/Analysis';
import AnalysisHeader from '../../shared/AnalysisHeader';
import AnalysisHeaderContent from '../../shared/AnalysisHeaderContent';
import AnalysisHeaderActions from '../../shared/AnalysisHeaderActions';
import AnalysisPie from '../../shared/AnalysisPie';
import AnalysisPieDetails from '../../shared/AnalysisPieDetails';
import AnalysisPieDetail from '../../shared/AnalysisPieDetail';
import {
	hasAudienceWidgets,
	AudienceWidgetsRenderer,
} from 'growthstack/slotfills/analytics-audience';



const AudienceMetricTooltip = ( props: { text: string } ) => {
	const { text } = props;

	return (
		<Tooltip
			text={ text }
			placement="top"
			delay={ 250 }
			className="gs-tooltip"
		>
			<div className="gs-tooltip-icon">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					fill="none"
					viewBox="0 0 14 16"
				>
					<path fill="#000" fillOpacity=".01" d="M0 1h14v14H0z" />
					<path
						fill="#aaa"
						d="M12.6875 7.75c0-2.0234-1.0937-3.8828-2.8438-4.9219-1.7773-1.0117-3.9375-1.0117-5.6875 0C2.379 3.8671 1.3125 5.7266 1.3125 7.75c0 2.0508 1.0664 3.9102 2.8438 4.9492 1.75 1.0117 3.9101 1.0117 5.6875 0 1.75-1.039 2.8437-2.8984 2.8437-4.9492ZM0 7.75c0-2.4883 1.3125-4.7852 3.5-6.043 2.1602-1.2578 4.8125-1.2578 7 0C12.6602 2.9648 14 5.2617 14 7.75c0 2.5156-1.3398 4.8125-3.5 6.0703-2.1875 1.2578-4.8398 1.2578-7 0C1.3125 12.5625 0 10.2656 0 7.75Zm4.621-2.461c.2188-.6288.793-1.039 1.4493-1.039h1.586c.957 0 1.75.793 1.75 1.75 0 .6016-.3555 1.1758-.875 1.4766l-.875.5195c-.0274.3555-.3008.6289-.6563.6289-.3828 0-.6563-.2734-.6563-.6563v-.3554c0-.2461.1094-.4649.3282-.5742l1.2031-.6836c.1367-.082.2188-.2188.2188-.3555 0-.246-.1915-.4102-.4375-.4102h-1.586c-.082 0-.164.0547-.1914.1368l-.0273.0273c-.1094.3555-.4922.5195-.8204.4102-.3554-.1368-.5195-.5196-.4101-.8477v-.0273Zm1.504 5.086c0-.4648.3828-.875.875-.875.4648 0 .875.4102.875.875 0 .4922-.4102.875-.875.875-.4922 0-.875-.3828-.875-.875Z"
					/>
				</svg>
			</div>
		</Tooltip>
	);
};

type AudienceWidgetProps = {
	title: string;
	metricName: string;
	metricTooltip?: string;
	isLoading: boolean;
	data: any;
	assetsFolder: string;
};

const AudienceWidget = ( props: AudienceWidgetProps ) => {
	return (
		<div className={ `gs-box ${ props.isLoading ? 'is-skeleton' : '' }` }>
			<Analysis>
				<AnalysisHeader>
					<AnalysisHeaderContent>
						<h2>{ props.title }</h2>
					</AnalysisHeaderContent>
					{ props.metricTooltip && (
						<AnalysisHeaderActions>
							<AudienceMetricTooltip
								text={ props.metricTooltip }
							/>
						</AnalysisHeaderActions>
					) }
				</AnalysisHeader>
				{ ! props.isLoading &&
					props.data !== false &&
					props.data !== null && (
						<>
							<AnalysisPie
								metric={ props.metricName }
								dataPoints={ props.data.pieData }
								annotationLabel={ props.data.annotationLabel }
								annotationValue={ props.data.annotationValue }
							/>
							<AnalysisPieDetails>
								{ props.data.details.map( ( point ) => (
									<AnalysisPieDetail
										key={ point.label }
										label={ point.label }
										value={ point.displayCount }
										percentage={ point.displayPercentage }
										color={ point.color }
										subPoints={ point.subPoints }
									/>
								) ) }
							</AnalysisPieDetails>
						</>
					) }
			</Analysis>
		</div>
	);
};

// Color palette matching the pro version
const AUDIENCE_COLORS = [
	'rgba(77, 168, 79, 1)',     // Green
	'rgba(205, 233, 222, 1)',   // Light green
	'rgba(117, 97, 219, 1)',    // Purple
	'rgba(194, 176, 251, 1)',   // Light purple
	'rgba(175, 181, 188, 1)',   // Gray
	'rgba(206, 211, 217, 1)',   // Light gray
	'rgba(245, 206, 148, 1)',   // Orange
	'rgba(252, 235, 197, 1)',   // Light orange
];

// Dummy data for demonstration
const getDummyData = ( metricType: string ) => {
	const dummyDataMap = {
		segment: {
			annotationLabel: __( 'Active Customers', 'liana-with-growthstack' ),
			annotationValue: '42%',
			pieData: [
				{ label: __( 'Active Customers', 'liana-with-growthstack' ), value: 5200, color: AUDIENCE_COLORS[0], displayValue: '5.2K (42%)' },
				{ label: __( 'Newsletter Subscribers', 'liana-with-growthstack' ), value: 3700, color: AUDIENCE_COLORS[1], displayValue: '3.7K (30%)' },
				{ label: __( 'Cart Abandoners', 'liana-with-growthstack' ), value: 2100, color: AUDIENCE_COLORS[2], displayValue: '2.1K (17%)' },
				{ label: __( 'VIP Members', 'liana-with-growthstack' ), value: 1400, color: AUDIENCE_COLORS[3], displayValue: '1.4K (11%)' },
			],
			details: [
				{ label: __( 'Active Customers', 'liana-with-growthstack' ), value: 'active_customers', displayCount: '5.2K', count: 5200, percentage: 42, displayPercentage: '42%', color: AUDIENCE_COLORS[0] },
				{ label: __( 'Newsletter Subscribers', 'liana-with-growthstack' ), value: 'newsletter', displayCount: '3.7K', count: 3700, percentage: 30, displayPercentage: '30%', color: AUDIENCE_COLORS[1] },
				{ label: __( 'Cart Abandoners', 'liana-with-growthstack' ), value: 'cart_abandoners', displayCount: '2.1K', count: 2100, percentage: 17, displayPercentage: '17%', color: AUDIENCE_COLORS[2] },
				{ label: __( 'VIP Members', 'liana-with-growthstack' ), value: 'vip', displayCount: '1.4K', count: 1400, percentage: 11, displayPercentage: '11%', color: AUDIENCE_COLORS[3] },
			],
		},
		source: {
			annotationLabel: __( 'Organic Search', 'liana-with-growthstack' ),
			annotationValue: '48%',
			pieData: [
				{ label: __( 'Organic Search', 'liana-with-growthstack' ), value: 5900, color: AUDIENCE_COLORS[0], displayValue: '5.9K (48%)' },
				{ label: __( 'Direct', 'liana-with-growthstack' ), value: 3200, color: AUDIENCE_COLORS[1], displayValue: '3.2K (26%)' },
				{ label: __( 'Social', 'liana-with-growthstack' ), value: 2000, color: AUDIENCE_COLORS[2], displayValue: '2.0K (16%)' },
				{ label: __( 'Referral', 'liana-with-growthstack' ), value: 1200, color: AUDIENCE_COLORS[3], displayValue: '1.2K (10%)' },
			],
			details: [
				{ label: __( 'Organic Search', 'liana-with-growthstack' ), value: 'organic', displayCount: '5.9K', count: 5900, percentage: 48, displayPercentage: '48%', color: AUDIENCE_COLORS[0] },
				{ label: __( 'Direct', 'liana-with-growthstack' ), value: 'direct', displayCount: '3.2K', count: 3200, percentage: 26, displayPercentage: '26%', color: AUDIENCE_COLORS[1] },
				{ label: __( 'Social', 'liana-with-growthstack' ), value: 'social', displayCount: '2.0K', count: 2000, percentage: 16, displayPercentage: '16%', color: AUDIENCE_COLORS[2] },
				{ label: __( 'Referral', 'liana-with-growthstack' ), value: 'referral', displayCount: '1.2K', count: 1200, percentage: 10, displayPercentage: '10%', color: AUDIENCE_COLORS[3] },
			],
		},
		device: {
			annotationLabel: __( 'Mobile', 'liana-with-growthstack' ),
			annotationValue: '52%',
			pieData: [
				{ label: __( 'Mobile', 'liana-with-growthstack' ), value: 6400, color: AUDIENCE_COLORS[0], displayValue: '6.4K (52%)' },
				{ label: __( 'Desktop', 'liana-with-growthstack' ), value: 4700, color: AUDIENCE_COLORS[1], displayValue: '4.7K (38%)' },
				{ label: __( 'Tablet', 'liana-with-growthstack' ), value: 1200, color: AUDIENCE_COLORS[2], displayValue: '1.2K (10%)' },
			],
			details: [
				{ label: __( 'Mobile', 'liana-with-growthstack' ), value: 'mobile', displayCount: '6.4K', count: 6400, percentage: 52, displayPercentage: '52%', color: AUDIENCE_COLORS[0] },
				{ label: __( 'Desktop', 'liana-with-growthstack' ), value: 'desktop', displayCount: '4.7K', count: 4700, percentage: 38, displayPercentage: '38%', color: AUDIENCE_COLORS[1] },
				{ label: __( 'Tablet', 'liana-with-growthstack' ), value: 'tablet', displayCount: '1.2K', count: 1200, percentage: 10, displayPercentage: '10%', color: AUDIENCE_COLORS[2] },
			],
		},
		new_returning: {
			annotationLabel: __( 'New', 'liana-with-growthstack' ),
			annotationValue: '60%',
			pieData: [
				{ label: __( 'New', 'liana-with-growthstack' ), value: 7400, color: AUDIENCE_COLORS[0], displayValue: '7.4K (60%)' },
				{ label: __( 'Returning', 'liana-with-growthstack' ), value: 4900, color: AUDIENCE_COLORS[1], displayValue: '4.9K (40%)' },
			],
			details: [
				{ label: __( 'New', 'liana-with-growthstack' ), value: 'new', displayCount: '7.4K', count: 7400, percentage: 60, displayPercentage: '60%', color: AUDIENCE_COLORS[0] },
				{ label: __( 'Returning', 'liana-with-growthstack' ), value: 'returning', displayCount: '4.9K', count: 4900, percentage: 40, displayPercentage: '40%', color: AUDIENCE_COLORS[1] },
			],
		},
		utm_campaign: {
			annotationLabel: 'summer_sale',
			annotationValue: '50%',
			pieData: [
				{ label: 'summer_sale', value: 1600, color: AUDIENCE_COLORS[0], displayValue: '1.6K (50%)' },
				{ label: 'newsletter', value: 960, color: AUDIENCE_COLORS[1], displayValue: '960 (30%)' },
				{ label: 'product_launch', value: 640, color: AUDIENCE_COLORS[2], displayValue: '640 (20%)' },
			],
			details: [
				{ label: 'summer_sale', value: 'summer_sale', displayCount: '1.6K', count: 1600, percentage: 50, displayPercentage: '50%', color: AUDIENCE_COLORS[0] },
				{ label: 'newsletter', value: 'newsletter', displayCount: '960', count: 960, percentage: 30, displayPercentage: '30%', color: AUDIENCE_COLORS[1] },
				{ label: 'product_launch', value: 'product_launch', displayCount: '640', count: 640, percentage: 20, displayPercentage: '20%', color: AUDIENCE_COLORS[2] },
			],
		},
		utm_source: {
			annotationLabel: 'google',
			annotationValue: '45%',
			pieData: [
				{ label: 'google', value: 1400, color: AUDIENCE_COLORS[0], displayValue: '1.4K (45%)' },
				{ label: 'facebook', value: 1100, color: AUDIENCE_COLORS[1], displayValue: '1.1K (35%)' },
				{ label: 'twitter', value: 640, color: AUDIENCE_COLORS[2], displayValue: '640 (20%)' },
			],
			details: [
				{ label: 'google', value: 'google', displayCount: '1.4K', count: 1400, percentage: 45, displayPercentage: '45%', color: AUDIENCE_COLORS[0] },
				{ label: 'facebook', value: 'facebook', displayCount: '1.1K', count: 1100, percentage: 35, displayPercentage: '35%', color: AUDIENCE_COLORS[1] },
				{ label: 'twitter', value: 'twitter', displayCount: '640', count: 640, percentage: 20, displayPercentage: '20%', color: AUDIENCE_COLORS[2] },
			],
		},
		utm_medium: {
			annotationLabel: 'cpc',
			annotationValue: '50%',
			pieData: [
				{ label: 'cpc', value: 1600, color: AUDIENCE_COLORS[0], displayValue: '1.6K (50%)' },
				{ label: 'email', value: 960, color: AUDIENCE_COLORS[1], displayValue: '960 (30%)' },
				{ label: 'social', value: 640, color: AUDIENCE_COLORS[2], displayValue: '640 (20%)' },
			],
			details: [
				{ label: 'cpc', value: 'cpc', displayCount: '1.6K', count: 1600, percentage: 50, displayPercentage: '50%', color: AUDIENCE_COLORS[0] },
				{ label: 'email', value: 'email', displayCount: '960', count: 960, percentage: 30, displayPercentage: '30%', color: AUDIENCE_COLORS[1] },
				{ label: 'social', value: 'social', displayCount: '640', count: 640, percentage: 20, displayPercentage: '20%', color: AUDIENCE_COLORS[2] },
			],
		},
		other_campaign: {
			annotationLabel: 'gclid',
			annotationValue: '60%',
			pieData: [
				{ label: 'gclid', value: 1300, color: AUDIENCE_COLORS[0], displayValue: '1.3K (60%)' },
				{ label: 'fbclid', value: 840, color: AUDIENCE_COLORS[1], displayValue: '840 (40%)' },
			],
			details: [
				{ label: 'gclid', value: 'gclid', displayCount: '1.3K', count: 1300, percentage: 60, displayPercentage: '60%', color: AUDIENCE_COLORS[0] },
				{ label: 'fbclid', value: 'fbclid', displayCount: '840', count: 840, percentage: 40, displayPercentage: '40%', color: AUDIENCE_COLORS[1] },
			],
		},
	};

	return dummyDataMap[ metricType ] || null;
};

export default function SiteAudience( props ) {
	const { assetsFolder, isLianaAutomationActive, lianaAdminPageUrl, upgradeUrl } =
		props;

	const [ hasWidgets, setHasWidgets ] = useState( hasAudienceWidgets() );

	// Listen for registry changes
	useEffect( () => {
		const checkInterval = setInterval( () => {
			const currentHasWidgets = hasAudienceWidgets();
			if ( currentHasWidgets !== hasWidgets ) {
				setHasWidgets( currentHasWidgets );
				clearInterval( checkInterval );
			}
		}, 100 );

		// Cleanup after 5 seconds max
		const timeout = setTimeout( () => {
			clearInterval( checkInterval );
		}, 5000 );

		return () => {
			clearInterval( checkInterval );
			clearTimeout( timeout );
		};
	}, [ hasWidgets ] );

	return (
		<>
			{ hasWidgets ? (
				<>
					<AudienceWidgetsRenderer
						assetsFolder={ assetsFolder }
						isLianaAutomationActive={ isLianaAutomationActive }
						lianaAdminPageUrl={ lianaAdminPageUrl }
					/>
				</>
			) : (
				<>
					<div className="gs-header-box">
						<div className="gs-header-box__main">
							<h2>{ __( 'Audience', 'liana-with-growthstack' ) }</h2>
						</div>
					</div>
					<div className={`growthstack-analytics-site-audience ${hasWidgets ? 'has-widgets' : 'is-placeholder'}`}>
						<div className="growthstack-analytics-site-audience-placeholder">
							<div className="growthstack-analytics-site-audience-placeholder__inner">
						<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 25 28" width="24" height="24"><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"/></svg>
						<p><strong>{ __( 'Available for Pro version', 'liana-with-growthstack' ) }</strong></p>
						<p>{ __( 'Unlock advanced audience insights with GrowthStack Pro. You can see information on your audience about LianaAutomation segments, traffic sources, device types, ads, UTM parameters and more.', 'liana-with-growthstack' ) }</p>
						{ upgradeUrl && (
							<a
								href={ upgradeUrl }
								target="_blank"
								className='gs-upgrade-button'
							>
								{ __( 'Upgrade to Pro', 'liana-with-growthstack' ) }
							</a>
						) }
					</div>
						</div>
						<AudienceWidget
							title={ __( 'LianaAutomation Segments', 'liana-with-growthstack' ) }
							metricName={ __( 'Segments', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'segment' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'Traffic Sources', 'liana-with-growthstack' ) }
							metricName={ __( 'Traffic source', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'source' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'New vs. Returning', 'liana-with-growthstack' ) }
							metricName={ __( 'New vs. Returning', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'new_returning' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'Device Type', 'liana-with-growthstack' ) }
							metricName={ __( 'Device type', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'device' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'UTM Campaign', 'liana-with-growthstack' ) }
							metricName={ __( 'UTM Campaign', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'utm_campaign' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'UTM Source', 'liana-with-growthstack' ) }
							metricName={ __( 'UTM Source', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'utm_source' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'UTM Medium', 'liana-with-growthstack' ) }
							metricName={ __( 'UTM Medium', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'utm_medium' ) }
							assetsFolder={ assetsFolder }
						/>
						<AudienceWidget
							title={ __( 'Other Campaign', 'liana-with-growthstack' ) }
							metricName={ __( 'Other Campaign', 'liana-with-growthstack' ) }
							isLoading={ false }
							data={ getDummyData( 'other_campaign' ) }
							assetsFolder={ assetsFolder }
						/>
					</div>
				</>
			) }
		</>
	);
}
