/**
 * WordPress dependencies
 */
import { Button } from '@safe-wordpress/components';
import { useEffect } from '@safe-wordpress/element';
import { _x, sprintf } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import clsx from 'clsx';
import { trim } from 'lodash';
import { usePageAttribute } from '@nab/data';
import { EMPTY_ARRAY, hasHead } from '@nab/utils';

/**
 * Internal dependencies
 */
import './style.scss';
import { useExperimentAttribute } from '../hooks';

export const SegmentList = (): JSX.Element => {
	const segments = useExperimentAttribute( 'segments' ) || EMPTY_ARRAY;
	const [ activeSegmentId, setActiveSegmentId ] = usePageAttribute(
		'editor/activeSegment',
		'default'
	);

	useEffect( () => {
		if ( 1 === segments.length && hasHead( segments ) ) {
			setActiveSegmentId( segments[ 0 ].id );
		}
	}, [ segments, setActiveSegmentId ] );

	return (
		<ul className="nab-segment-list">
			{ segments.length > 1 && (
				<li
					key="default"
					className={ clsx( 'nab-segment-list__item', {
						'nab-segment-list__item--is-active':
							'default' === activeSegmentId,
					} ) }
				>
					<Button
						disabled={ 'default' === activeSegmentId }
						title={ _x(
							'Combined Segment',
							'text',
							'nelio-ab-testing'
						) }
						onClick={ () => setActiveSegmentId( 'default' ) }
					>
						{ _x( 'Combined Segment', 'text', 'nelio-ab-testing' ) }
					</Button>
				</li>
			) }

			{ segments.map( ( segment, index ) => (
				<li
					key={ segment.id }
					className={ clsx( 'nab-segment-list__item', {
						'nab-segment-list__item--is-active':
							segment.id === activeSegmentId,
					} ) }
				>
					<Button
						disabled={ segment.id === activeSegmentId }
						title={
							trim( segment.attributes.name ) ||
							getDefaultName( index )
						}
						onClick={ () => setActiveSegmentId( segment.id ) }
					>
						{ trim( segment.attributes.name ) ||
							getDefaultName( index ) }
					</Button>
				</li>
			) ) }
		</ul>
	);
};

// =======
// HELPERS
// =======

const getDefaultName = ( index: number ) =>
	sprintf(
		/* translators: %d: Segment index. */
		_x( 'Segment %d', 'text', 'nelio-ab-testing' ),
		index + 1
	);
