/**
 * Template Library — grid of predefined query templates.
 *
 * @package RawTypeOE
 */

import { useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import {
	Badge,
	Button,
	Card,
	CardContent,
	CardFooter,
	CardHeader,
	CardTitle,
	EmptyState,
	Notice,
	Skeleton,
	SkeletonGroup,
	Tabs,
	SearchField,
} from '@rawtype/ui';
import { useTemplates } from '../hooks/useTemplates';

function TemplatesSkeleton() {
	return (
		<SkeletonGroup>
			<div className="roe-template-library__toolbar">
				<Skeleton width={ 240 } height={ 40 } />
				<Skeleton width={ 320 } height={ 36 } />
			</div>
			<div className="roe-template-library__grid">
				{ Array.from( { length: 6 } ).map( ( _, i ) => (
					<Skeleton key={ i } width="100%" height={ 180 } />
				) ) }
			</div>
		</SkeletonGroup>
	);
}

function getEntityLabel( entity ) {
	const map = {
		orders: __( 'Orders', 'rawtype-order-exporter-woocommerce' ),
		products: __( 'Products', 'rawtype-order-exporter-woocommerce' ),
		customers: __( 'Customers', 'rawtype-order-exporter-woocommerce' ),
	};
	return map[ entity ] || entity;
}

export default function TemplateLibrary( { onSelectTemplate } ) {
	const { templates, isLoading, error } = useTemplates( null );
	const [ search, setSearch ] = useState( '' );
	const [ entityFilter, setEntityFilter ] = useState( 'all' );

	if ( isLoading ) {
		return (
			<div className="roe-template-library">
				<TemplatesSkeleton />
			</div>
		);
	}

	if ( error ) {
		return (
			<div className="roe-template-library">
				<Notice type="error">
					{ __( 'Error loading templates. Reload the page.', 'rawtype-order-exporter-woocommerce' ) }
				</Notice>
				<Button type="button" onClick={ () => window.location.reload() }>
					{ __( 'Reload', 'rawtype-order-exporter-woocommerce' ) }
				</Button>
			</div>
		);
	}

	if ( ! templates || 0 === templates.length ) {
		return (
			<div className="roe-template-library">
				<EmptyState
					title={ __( 'No templates available', 'rawtype-order-exporter-woocommerce' ) }
					description={ __( 'No predefined templates are available at this time.', 'rawtype-order-exporter-woocommerce' ) }
				/>
			</div>
		);
	}

	const filtered = templates.filter( ( tpl ) => {
		const matchesSearch =
			! search ||
			tpl.name.toLowerCase().indexOf( search.toLowerCase() ) !== -1 ||
			tpl.description.toLowerCase().indexOf( search.toLowerCase() ) !== -1;
		const matchesEntity =
			'all' === entityFilter || tpl.entity === entityFilter;
		return matchesSearch && matchesEntity;
	} );

	return (
		<div className="roe-template-library">
			<div className="roe-template-library__toolbar">
				<SearchField
					placeholder={ __( 'Search templates...', 'rawtype-order-exporter-woocommerce' ) }
					value={ search }
					onChange={ setSearch }
				/>
				<Tabs.Root
					value={ entityFilter }
					onValueChange={ setEntityFilter }
				>
					<Tabs.List>
						<Tabs.Trigger value="all">
							{ __( 'All', 'rawtype-order-exporter-woocommerce' ) }
						</Tabs.Trigger>
						<Tabs.Trigger value="orders">
							{ __( 'Orders', 'rawtype-order-exporter-woocommerce' ) }
						</Tabs.Trigger>
						<Tabs.Trigger value="products">
							{ __( 'Products', 'rawtype-order-exporter-woocommerce' ) }
						</Tabs.Trigger>
						<Tabs.Trigger value="customers">
							{ __( 'Customers', 'rawtype-order-exporter-woocommerce' ) }
						</Tabs.Trigger>
					</Tabs.List>
				</Tabs.Root>
			</div>

			<div className="roe-template-library__grid">
				{ filtered.map( ( template ) => (
					<Card key={ template.id } className="roe-template-card">
						<CardHeader className="roe-template-card__header">
							<span
								className={ `roe-template-card__icon dashicons dashicons-${ template.icon }` }
								aria-hidden="true"
							/>
							<CardTitle as="h4">{ template.name }</CardTitle>
						</CardHeader>
						<CardContent className="roe-template-card__body">
							<p className="roe-template-card__desc">
								{ template.description }
							</p>
							<div className="roe-template-card__tags">
								<Badge>
									{ getEntityLabel( template.entity ) }
								</Badge>
								{ template.category && (
									<Badge variant="default">{ template.category }</Badge>
								) }
							</div>
						</CardContent>
						<CardFooter className="roe-template-card__footer">
							<Button
								type="button"
								size="sm"
								onClick={ () => onSelectTemplate( template ) }
							>
								{ __( 'Export', 'rawtype-order-exporter-woocommerce' ) }
							</Button>
						</CardFooter>
					</Card>
				) ) }
			</div>

			{ 0 === filtered.length && (
				<EmptyState
					title={ __( 'No results', 'rawtype-order-exporter-woocommerce' ) }
					description={ sprintf(
						/* translators: %s: search term */
						__( 'No template matches "%s". Try another search.', 'rawtype-order-exporter-woocommerce' ),
						search,
					) }
				/>
			) }
		</div>
	);
}
