/**
 * Entity selector component (Step 1 of wizard).
 *
 * @package RawTypeOE
 */

import { __, _n, sprintf } from '@wordpress/i18n';
import { applyFilters } from '@wordpress/hooks';
import {
	Badge,
	Button,
	Card,
	CardContent,
	CardDescription,
	CardHeader,
	CardTitle,
	EmptyState,
	Notice,
	Skeleton,
	SkeletonGroup,
} from '@rawtype/ui';

const DEFAULT_ENTITIES = [
	{
		id: 'orders',
		title: __( 'Orders', 'rawtype-order-exporter-woocommerce' ),
		description: __(
			'ID, status, date, totals, billing and shipping data, items, coupons',
			'rawtype-order-exporter-woocommerce',
		),
		icon: 'archive',
		countKey: 'orders',
	},
	{
		id: 'products',
		title: __( 'Products', 'rawtype-order-exporter-woocommerce' ),
		description: __(
			'Name, SKU, price, stock, categories, attributes, images',
			'rawtype-order-exporter-woocommerce',
		),
		icon: 'tag',
		countKey: 'products',
	},
	{
		id: 'customers',
		title: __( 'Customers', 'rawtype-order-exporter-woocommerce' ),
		description: __(
			'Name, email, address, total spent, order count, last order',
			'rawtype-order-exporter-woocommerce',
		),
		icon: 'groups',
		countKey: 'customers',
	},
	{
		id: 'cross-entity',
		title: __( 'Cross-Entity', 'rawtype-order-exporter-woocommerce' ),
		description: __(
			'Cross-reference orders, products, and customers in a single query',
			'rawtype-order-exporter-woocommerce',
		),
		icon: 'networking',
		countKey: 'orders',
		subtitle: __( 'Advanced queries', 'rawtype-order-exporter-woocommerce' ),
		style: 'cross-entity',
	},
];

function EntityCardSkeleton() {
	return (
		<SkeletonGroup className="roe-entity-cards">
			{ [ 1, 2, 3 ].map( ( i ) => (
				<Card key={ i } className="roe-entity-card">
					<CardContent>
						<Skeleton width={ 40 } height={ 40 } />
						<Skeleton width={ 120 } height={ 24 } />
						<Skeleton width="100%" height={ 16 } />
						<Skeleton width={ 80 } height={ 24 } />
					</CardContent>
				</Card>
			) ) }
		</SkeletonGroup>
	);
}

export default function EntitySelector( {
	selectedEntity,
	onSelect,
	counts,
	countsLoading,
	countsError,
	onRetry,
	onNext,
} ) {
	/**
	 * Filter available entities for the selector.
	 * Pro can add "Cross-Entity" card via this filter.
	 */
	const entities = applyFilters(
		'rawtype_oe_entities',
		DEFAULT_ENTITIES,
	);

	if ( countsLoading ) {
		return <EntityCardSkeleton />;
	}

	if ( countsError ) {
		return (
			<div className="roe-entity-selector">
				<Notice type="error">
					{ __(
						'Could not load store data. Verify that WooCommerce is active.',
						'rawtype-order-exporter-woocommerce',
					) }
				</Notice>
				{ onRetry && (
					<Button
						type="button"
						variant="outline"
						size="sm"
						onClick={ onRetry }
					>
						{ __( 'Retry', 'rawtype-order-exporter-woocommerce' ) }
					</Button>
				) }
			</div>
		);
	}

	return (
		<div className="roe-entity-selector">
			<div className="roe-entity-cards">
				{ entities.map( ( ent ) => {
					const count = counts ? counts[ ent.countKey ] || 0 : 0;
					const isSelected = selectedEntity === ent.id;
					const isEmpty = 0 === count;

					return (
						<Card
							key={ ent.id }
							className={
								'roe-entity-card' +
								( isSelected ? ' roe-entity-card--selected' : '' ) +
								( isEmpty ? ' roe-entity-card--empty' : '' ) +
								( 'cross-entity' === ent.style ? ' roe-entity-card--cross' : '' )
							}
							onClick={ () => onSelect( ent.id ) }
							role="button"
							tabIndex={ 0 }
							onKeyDown={ ( e ) => {
								if ( 'Enter' === e.key || ' ' === e.key ) {
									e.preventDefault();
									onSelect( ent.id );
								}
							} }
						>
							<CardHeader>
								<span
									className={ `roe-entity-card-icon dashicons dashicons-${ ent.icon }` }
									aria-hidden="true"
								/>
								<CardTitle>
									{ ent.title }
									{ ent.badge && (
										<Badge variant="accent" className="roe-entity-card-badge">
											{ ent.badge }
										</Badge>
									) }
								</CardTitle>
								{ ent.subtitle && (
									<CardDescription className="roe-entity-card-subtitle">
										{ ent.subtitle }
									</CardDescription>
								) }
							</CardHeader>
							<CardContent>
								<CardDescription>
									{ ent.description }
								</CardDescription>
								<div className="roe-entity-card-count">
									<Badge variant={ isEmpty ? 'outline' : 'inset' }>
										{ sprintf(
											_n(
												'%d record',
												'%d records',
												count,
												'rawtype-order-exporter-woocommerce',
											),
											count,
										) }
									</Badge>
								</div>
								{ isEmpty && (
									<p className="roe-entity-card-empty-text">
										{ ent.id === 'orders' &&
											__( 'Your store has no orders yet', 'rawtype-order-exporter-woocommerce' ) }
										{ ent.id === 'products' &&
											__( 'Your store has no products yet', 'rawtype-order-exporter-woocommerce' ) }
										{ ent.id === 'customers' &&
											__( 'Your store has no customers yet', 'rawtype-order-exporter-woocommerce' ) }
									</p>
								) }
							</CardContent>
						</Card>
					);
				} ) }
			</div>

			<div className="roe-entity-actions">
				<Button
					type="button"
					onClick={ onNext }
					disabled={ ! selectedEntity }
				>
					{ __( 'Next', 'rawtype-order-exporter-woocommerce' ) }
				</Button>
			</div>
		</div>
	);
}
