/**
 * Profile Manager — list, run, edit, and delete saved export profiles.
 *
 * @package RawTypeOE
 */

import { useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { applyFilters } from '@wordpress/hooks';
import {
	Badge,
	Button,
	CardDescription,
	CardTitle,
	Dialog,
	DropdownMenu,
	EmptyState,
	Notice,
	Select,
	Skeleton,
	SkeletonGroup,
	Table,
	Tooltip,
} from '@rawtype/ui';
import { useProfiles } from '../hooks/useProfiles';

function ProfilesSkeleton() {
	return (
		<SkeletonGroup>
			<Skeleton width={ 200 } height={ 24 } />
			{ Array.from( { length: 3 } ).map( ( _, i ) => (
				<Skeleton key={ i } width="100%" height={ 48 } />
			) ) }
		</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 ProfileManager( { onEditProfile, onRunComplete, onCreateExport } ) {
	const {
		profiles,
		isLoading,
		error,
		runProfile,
		deleteProfile,
		isRunning,
	} = useProfiles();

	const [ deleteConfirm, setDeleteConfirm ] = useState( null );
	const [ formatOverrides, setFormatOverrides ] = useState( {} );

	const getFormat = ( profile ) =>
		formatOverrides[ profile.id ] || profile.format || 'csv';

	const setFormat = ( profileId, format ) =>
		setFormatOverrides( ( prev ) => ( { ...prev, [ profileId ]: format } ) );
	if ( isLoading ) {
		return (
			<div className="roe-profile-manager">
				<ProfilesSkeleton />
			</div>
		);
	}

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

	if ( ! profiles || 0 === profiles.length ) {
		return (
			<div className="roe-profile-manager">
				<EmptyState
					title={ __( 'No saved profiles', 'rawtype-order-exporter-woocommerce' ) }
					description={ __(
						'Create your first export and save it as a profile to reuse it with a single click.',
						'rawtype-order-exporter-woocommerce',
					) }
					action={
						onCreateExport ? (
							<Button type="button" onClick={ onCreateExport }>
								{ __( 'New export', 'rawtype-order-exporter-woocommerce' ) }
							</Button>
						) : undefined
					}
				/>
			</div>
		);
	}

	const handleRun = async ( profileId ) => {
		const format = formatOverrides[ profileId ];
		const result = await runProfile( profileId, format );
		if ( result && result.download_url ) {
			window.location.href = result.download_url;
			if ( onRunComplete ) {
				onRunComplete( result );
			}
		}
	};

	const handleDelete = async ( profileId ) => {
		await deleteProfile( profileId );
		setDeleteConfirm( null );
	};

	/**
	 * Filter the profile list for Pro extensibility.
	 *
	 * @param {Array} profiles Array of profile objects.
	 */
	const filteredProfiles = applyFilters(
		'rawtype_oe_profiles_list',
		profiles,
	);

	return (
		<div className="roe-profile-manager">
			<div className="roe-profile-manager__header">
				<CardTitle as="h2">{ __( 'Export profiles', 'rawtype-order-exporter-woocommerce' ) }</CardTitle>
				<CardDescription>
					{ __( 'Your saved exports. Run any profile with a single click.', 'rawtype-order-exporter-woocommerce' ) }
				</CardDescription>
			</div>

			<Table.Root>
				<Table.Head>
					<Table.Row>
						<Table.HeaderCell>
							{ __( 'Name', 'rawtype-order-exporter-woocommerce' ) }
						</Table.HeaderCell>
						<Table.HeaderCell>
							{ __( 'Entity', 'rawtype-order-exporter-woocommerce' ) }
						</Table.HeaderCell>
						<Table.HeaderCell>
							{ __( 'Format', 'rawtype-order-exporter-woocommerce' ) }
						</Table.HeaderCell>
						<Table.HeaderCell>
							{ __( 'Last run', 'rawtype-order-exporter-woocommerce' ) }
						</Table.HeaderCell>
						<Table.HeaderCell>
							{ __( 'Records', 'rawtype-order-exporter-woocommerce' ) }
						</Table.HeaderCell>
						<Table.HeaderCell />
					</Table.Row>
				</Table.Head>
				<Table.Body>
					{ filteredProfiles.map( ( profile ) => (
						<Table.Row key={ profile.id }>
							<Table.Cell>
								<strong>{ profile.name }</strong>
							</Table.Cell>
							<Table.Cell>
								<Badge>
									{ getEntityLabel( profile.entity ) }
								</Badge>
							</Table.Cell>
							<Table.Cell>
								<Select.Root
									value={ getFormat( profile ) }
									onValueChange={ ( value ) =>
										setFormat( profile.id, value )
									}
								>
									<Select.Trigger placeholder={ __( 'Format', 'rawtype-order-exporter-woocommerce' ) } />
									<Select.Content>
										<Select.Item value="csv">CSV</Select.Item>
										<Select.Item value="xlsx">Excel (XLSX)</Select.Item>
									</Select.Content>
								</Select.Root>
							</Table.Cell>
							<Table.Cell>
								{ profile.last_run_date ||
									__( 'Never', 'rawtype-order-exporter-woocommerce' ) }
							</Table.Cell>
							<Table.Cell>
								{ profile.last_run_count || '\u2014' }
							</Table.Cell>
							<Table.Cell>
								<div className="roe-profile-table__actions">
									<Button
										type="button"
										size="sm"
										onClick={ () => handleRun( profile.id ) }
										disabled={ isRunning === profile.id }
									>
										{ isRunning === profile.id
											? __( 'Exporting…', 'rawtype-order-exporter-woocommerce' )
											: __( 'Run', 'rawtype-order-exporter-woocommerce' ) }
									</Button>
									<DropdownMenu.Root>
										<Tooltip content={ __( 'More actions', 'rawtype-order-exporter-woocommerce' ) }>
											<DropdownMenu.Trigger asChild>
												<Button
													type="button"
													variant="outline"
													size="icon"
													aria-label={ __( 'More actions', 'rawtype-order-exporter-woocommerce' ) }
												>
													&#8943;
												</Button>
											</DropdownMenu.Trigger>
										</Tooltip>
										<DropdownMenu.Content align="end">
											<DropdownMenu.Item
												onSelect={ () => onEditProfile( profile ) }
											>
												{ __( 'Edit', 'rawtype-order-exporter-woocommerce' ) }
											</DropdownMenu.Item>
											<DropdownMenu.Separator />
											<DropdownMenu.Item
												destructive
												onSelect={ () =>
													setDeleteConfirm( profile.id )
												}
											>
												{ __( 'Delete', 'rawtype-order-exporter-woocommerce' ) }
											</DropdownMenu.Item>
										</DropdownMenu.Content>
									</DropdownMenu.Root>
								</div>
							</Table.Cell>
						</Table.Row>
					) ) }
				</Table.Body>
			</Table.Root>

			{ deleteConfirm && (
				<Dialog.Root
					open={ true }
					onOpenChange={ ( open ) => {
						if ( ! open ) {
							setDeleteConfirm( null );
						}
					} }
				>
					<Dialog.Content>
						<Dialog.Title>
							{ __( 'Delete profile', 'rawtype-order-exporter-woocommerce' ) }
						</Dialog.Title>
						<Dialog.Description>
							{ __(
								'Are you sure you want to delete this profile? This action cannot be undone.',
								'rawtype-order-exporter-woocommerce',
							) }
						</Dialog.Description>
						<div className="roe-dialog-actions">
							<Button
								type="button"
								variant="outline"
								onClick={ () => setDeleteConfirm( null ) }
							>
								{ __( 'Cancel', 'rawtype-order-exporter-woocommerce' ) }
							</Button>
							<Button
								type="button"
								variant="outline"
								onClick={ () => handleDelete( deleteConfirm ) }
							>
								{ __( 'Delete', 'rawtype-order-exporter-woocommerce' ) }
							</Button>
						</div>
					</Dialog.Content>
				</Dialog.Root>
			) }

		</div>
	);
}
