/**
 * Filter Builder — container for filter chips, add button, count display.
 *
 * @package RawTypeOE
 */

import { useCallback, useMemo, useRef } from '@wordpress/element';
import { __, _n, _x, sprintf } from '@wordpress/i18n';
import { applyFilters } from '@wordpress/hooks';
import {
	Badge,
	Button,
	Card,
	CardContent,
	CardDescription,
	CardFooter,
	CardHeader,
	CardTitle,
	Checkbox,
	DropdownMenu,
	EmptyState,
	Label,
	Notice,
	Select,
	ToggleGroup,
	Tooltip,
} from '@rawtype/ui';
import {
	isValidCrossEntitySelection,
	sanitizeKey,
} from '../utils/crossEntity';
import FilterChip from './FilterChip';

/**
 * Default filter types available per entity.
 * Pro extends this via applyFilters('rawtype_oe_filter_types', types, entity).
 */
function getDefaultFilterTypes( entity ) {
	if ( 'cross-entity' === entity ) {
		return [
			{
				type: 'date',
				label: __( 'Order date', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'status',
				label: __( 'Order status', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'category',
				label: __( 'Product category', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'order_total',
				label: __( 'Order total', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'customer_total_spend',
				label: __( 'Total spent', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'customer_orders_count',
				label: __( 'Customer order count', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'product_price',
				label: __( 'Product price', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
		];
	}

	const types = [
		{
			type: 'date',
			label: __( 'Date', 'rawtype-order-exporter-woocommerce' ),
			enabled: true,
		},
		{
			type: 'status',
			label:
				'orders' === entity
					? __( 'Order status', 'rawtype-order-exporter-woocommerce' )
					: 'products' === entity
					? __( 'Product status', 'rawtype-order-exporter-woocommerce' )
					: __( 'Customer role', 'rawtype-order-exporter-woocommerce' ),
			enabled: true,
		},
	];

	// Product-related filters (for orders and products entities).
	if ( 'orders' === entity || 'products' === entity ) {
		types.push(
			{
				type: 'category',
				label: __( 'Product category', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'tag',
				label: __( 'Product tag', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'product',
				label: __( 'Specific product', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'sku',
				label: __( 'SKU', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
		);
	}

	// Numeric filters (entity-specific).
	if ( 'orders' === entity ) {
		types.push( {
			type: 'order_total',
			label: __( 'Order total', 'rawtype-order-exporter-woocommerce' ),
			enabled: true,
		} );
	}

	if ( 'customers' === entity ) {
		types.push(
			{
				type: 'customer_total_spend',
				label: __( 'Total spent', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
			{
				type: 'customer_orders_count',
				label: __( 'Order count', 'rawtype-order-exporter-woocommerce' ),
				enabled: true,
			},
		);
	}

	if ( 'products' === entity ) {
		types.push( {
			type: 'product_price',
			label: __( 'Product price', 'rawtype-order-exporter-woocommerce' ),
			enabled: true,
		} );
	}

	return types;
}

function getDefaultDateRange() {
	const now = new Date();
	const today = now.toISOString().split( 'T' )[ 0 ];
	const oneYearAgo = new Date( now );
	oneYearAgo.setFullYear( oneYearAgo.getFullYear() - 1 );
	const yearAgoStr = oneYearAgo.toISOString().split( 'T' )[ 0 ];
	return [ yearAgoStr, today ];
}

function getDefaultValue( type, entity ) {
	switch ( type ) {
		case 'date': {
			const defaultFields = {
				orders: 'date_created',
				products: 'date_created',
				customers: 'date_registered',
				'cross-entity': 'date_created',
			};
			return {
				type: 'date',
				field: defaultFields[ entity ] || 'date_created',
				operator: 'between',
				value: getDefaultDateRange(),
			};
		}
		case 'status':
			return {
				type: 'status',
				value: '',
			};
		case 'category':
			return {
				type: 'category',
				value: [],
			};
		case 'tag':
			return {
				type: 'tag',
				value: [],
			};
		case 'product':
			return {
				type: 'product',
				value: [],
				selectedProducts: [],
			};
		case 'sku':
			return {
				type: 'sku',
				value: '',
				mode: 'exact',
			};
		case 'order_total':
		case 'customer_total_spend':
		case 'customer_orders_count':
		case 'product_price':
			return {
				type,
				operator: '>',
				value: 0,
			};
		default:
			return { type };
	}
}

export default function FilterBuilder( {
	entity,
	crossEntityConfig,
	crossEntityValid,
	onSetCrossPrimary,
	onToggleCrossRelated,
	filters,
	logic,
	onSetLogic,
	onAddFilter,
	onUpdateFilter,
	onRemoveFilter,
	previewCount,
	previewLoading,
	previewError,
	onNext,
	onPrev,
} ) {
	// Keep last known count so we can show it dimmed while loading.
	const lastCountRef = useRef( previewCount );
	if ( ! previewLoading && null !== previewCount ) {
		lastCountRef.current = previewCount;
	}
	const displayCount = previewLoading ? lastCountRef.current : previewCount;

	const filterTypes = useMemo( () => {
		const defaults = getDefaultFilterTypes( entity );

		/**
		 * Filter available filter types per entity.
		 * Pro adds category, amount, custom field filters here.
		 */
		return applyFilters(
			'rawtype_oe_filter_types',
			defaults,
			entity,
		);
	}, [ entity ] );

	const crossPrimary = crossEntityConfig?.primary_entity || 'orders';
	const crossRelated = Array.isArray( crossEntityConfig?.related_entities )
		? crossEntityConfig.related_entities
		: [];
	const crossSelected = [ ...new Set(
		[ crossPrimary ].concat( crossRelated ).map( sanitizeKey ).filter( Boolean ),
	) ].sort();

	const crossOptions = [
		{ id: 'orders', label: __( 'Orders', 'rawtype-order-exporter-woocommerce' ) },
		{ id: 'customers', label: __( 'Customers', 'rawtype-order-exporter-woocommerce' ) },
		{ id: 'products', label: __( 'Products', 'rawtype-order-exporter-woocommerce' ) },
	];

	const handleAddFilter = useCallback(
		( type ) => {
			onAddFilter( getDefaultValue( type, entity ) );
		},
		[ onAddFilter, entity ],
	);

	const handleUpdate = useCallback(
		( filterId, updated ) => {
			onUpdateFilter( filterId, updated );
		},
		[ onUpdateFilter ],
	);

	const descriptionText = () => {
		if ( filters.length > 0 && previewError ) {
			return (
				<span className="roe-filter-count-inline roe-filter-count-inline--error">
					{ __( 'Error calculating records', 'rawtype-order-exporter-woocommerce' ) }
				</span>
			);
		}
		if ( filters.length > 0 && null !== displayCount ) {
			return (
				<span className={ 'roe-filter-count-inline' + ( previewLoading ? ' roe-filter-count-inline--loading' : '' ) }>
					{ sprintf(
						/* translators: %d: number of matching records */
						_n(
							'%d record matches the applied filters',
							'%d records match the applied filters',
							displayCount,
							'rawtype-order-exporter-woocommerce',
						),
						displayCount,
					) }
				</span>
			);
		}
		return __( 'Define conditions to filter the records to be exported. Without filters, all available records will be exported.', 'rawtype-order-exporter-woocommerce' );
	};

	return (
		<Card className="roe-filter-builder">
			<CardHeader>
				<CardTitle className="roe-filter-title">
					{ __( 'Filters', 'rawtype-order-exporter-woocommerce' ) }
					{ filters.length > 0 && (
						<Badge variant="inset" className="roe-filter-title-count">
							{ filters.length }
						</Badge>
					) }
				</CardTitle>
				<CardDescription>
					{ descriptionText() }
				</CardDescription>
			</CardHeader>

			<CardContent className="roe-filter-builder-content">
				{ 'cross-entity' === entity && (
					<div className="roe-cross-entity-config">
						<CardTitle as="h4">
							{ __( 'Cross-Entity Configuration', 'rawtype-order-exporter-woocommerce' ) }
						</CardTitle>
						<CardDescription>
							{ __( 'Select primary entity and relationships to build a unified query.', 'rawtype-order-exporter-woocommerce' ) }
						</CardDescription>

						<div className="roe-cross-entity-primary">
							<Label htmlFor="roe-cross-primary">
								{ __( 'Primary entity', 'rawtype-order-exporter-woocommerce' ) }
							</Label>
							<Select.Root value={ crossPrimary } onValueChange={ onSetCrossPrimary }>
								<Select.Trigger id="roe-cross-primary" />
								<Select.Content>
									{ crossOptions.map( ( option ) => (
										<Select.Item key={ option.id } value={ option.id }>
											{ option.label }
										</Select.Item>
									) ) }
								</Select.Content>
							</Select.Root>
						</div>

						<div className="roe-cross-entity-related">
							<Label>{ __( 'Related entities', 'rawtype-order-exporter-woocommerce' ) }</Label>
							<div className="roe-cross-entity-related-grid">
								{ crossOptions
									.filter( ( option ) => option.id !== crossPrimary )
									.map( ( option ) => {
										const checked = crossRelated.includes( option.id );
										const nextSelection = checked
											? crossSelected.filter( ( selected ) => selected !== option.id )
											: [ ...crossSelected, option.id ];
										const disabled = nextSelection.length > 1 && ! isValidCrossEntitySelection( nextSelection );
										const tooltip = disabled
											? __( 'Invalid combination: Orders must be part of the relationship.', 'rawtype-order-exporter-woocommerce' )
											: '';

										return (
											<Tooltip
												key={ option.id }
												content={ tooltip || undefined }
											>
											<div
												className="roe-cross-entity-related-item"
											>
												<Checkbox
													id={ 'roe-cross-related-' + option.id }
													checked={ checked }
													disabled={ disabled }
													onCheckedChange={ () => onToggleCrossRelated( option.id ) }
													label={ option.label }
												/>
											</div>
											</Tooltip>
										);
									} ) }
							</div>
						</div>

						{ ! crossEntityValid && (
							<Notice type="warning">
								{ __( 'Invalid combination. Use Customers+Orders, Orders+Products, or Customers+Orders+Products.', 'rawtype-order-exporter-woocommerce' ) }
							</Notice>
						) }
					</div>
				) }

				<div className="roe-filter-toolbar">
					<DropdownMenu.Root>
						<DropdownMenu.Trigger asChild>
							<Button
								type="button"
								variant="outline"
								size="sm"
							>
								{ __( 'Add filter', 'rawtype-order-exporter-woocommerce' ) }
							</Button>
						</DropdownMenu.Trigger>
						<DropdownMenu.Content align="start">
							{ filterTypes.map( ( ft ) => (
								<DropdownMenu.Item
									key={ ft.type }
									disabled={ ! ft.enabled }
									onSelect={ () => handleAddFilter( ft.type ) }
								>
									{ ft.label }
									{ ft.badge && (
										<Badge variant="accent" className="roe-filter-menu-pro-badge">
											{ ft.badge }
										</Badge>
									) }
								</DropdownMenu.Item>
							) ) }
						</DropdownMenu.Content>
					</DropdownMenu.Root>

					{ filters.length > 1 && (
						<div className="roe-filter-logic">
							<span>{ __( 'Combine filters with:', 'rawtype-order-exporter-woocommerce' ) }</span>
							<ToggleGroup.Root
								type="single"
								value={ logic }
								onValueChange={ ( val ) => {
									if ( val ) {
										onSetLogic( val );
									}
								} }
							>
								<ToggleGroup.Item value="and">
									{ _x( 'AND', 'filter combination logic', 'rawtype-order-exporter-woocommerce' ) }
								</ToggleGroup.Item>
								<ToggleGroup.Item value="or">
									{ _x( 'OR', 'filter combination logic', 'rawtype-order-exporter-woocommerce' ) }
								</ToggleGroup.Item>
							</ToggleGroup.Root>
						</div>
					) }
				</div>

				{ 0 === filters.length && (
					<EmptyState
						icon={ <span className="dashicons dashicons-filter" aria-hidden="true" /> }
						title={ __( 'No filters applied', 'rawtype-order-exporter-woocommerce' ) }
						description={
							null !== previewCount
								? sprintf(
										/* translators: %d: number of records */
										_n(
											'The %d available record will be exported',
											'The %d available records will be exported',
											previewCount,
											'rawtype-order-exporter-woocommerce',
										),
										previewCount,
								  )
								: __( 'All available records will be exported', 'rawtype-order-exporter-woocommerce' )
						}
					/>
				) }

				{ filters.length > 0 && (
					<div className="roe-filter-chips">
						{ filters.map( ( filter ) => (
							<FilterChip
								key={ filter.id }
								filter={ filter }
								entity={ entity }
								onUpdate={ handleUpdate }
								onRemove={ onRemoveFilter }
							/>
						) ) }
					</div>
				) }
			</CardContent>

			<CardFooter className="roe-filter-actions">
				<Button type="button" variant="outline" onClick={ onPrev }>
					{ __( 'Previous', 'rawtype-order-exporter-woocommerce' ) }
				</Button>
				<Button
					type="button"
					onClick={ onNext }
					disabled={ 'cross-entity' === entity && ! crossEntityValid }
				>
					{ __( 'Next', 'rawtype-order-exporter-woocommerce' ) }
				</Button>
			</CardFooter>
		</Card>
	);
}
