/**
 * Form Mappings — the list view. Target lists are resolved against the
 * cached Brevo data so a row reads as names, not ids.
 */
import { useCallback, useEffect, useState } from '@wordpress/element';
import Dialog from '../../components/Dialog';
import { __, sprintf } from '@wordpress/i18n';
import { useNavigate } from 'react-router-dom';

import {
	BlockStack,
	EmptyState,
	InlineStack,
	Note,
	SkeletonLoader,
} from '../../ui/molecules';
import { Button, Icon, Switcher, Text } from '../../ui/atoms';
import Section from '../../components/Section';
import StatusBadge from '../../components/StatusBadge';
import {
	deleteFeed,
	duplicateFeed,
	fetchFeeds,
	updateFeed,
} from '../../api/feeds';
import { useApp } from '../../store/AppStore';
import { formatRelative } from '../../utils/format';

export default function Mappings() {
	const { brevo, loadBrevo, addToast } = useApp();
	const navigate = useNavigate();

	const [ loading, setLoading ] = useState( true );
	const [ error, setError ] = useState( '' );
	const [ feeds, setFeeds ] = useState( [] );
	const [ pendingDelete, setPendingDelete ] = useState( null );
	const [ busyId, setBusyId ] = useState( 0 );

	const load = useCallback( async () => {
		setLoading( true );
		setError( '' );

		try {
			const response = await fetchFeeds();

			setFeeds( response.items || [] );
		} catch ( requestError ) {
			setError( requestError.message );
		} finally {
			setLoading( false );
		}
	}, [] );

	useEffect( () => {
		load();
		loadBrevo();
	}, [ load, loadBrevo ] );

	const listNames = ( ids ) => {
		if ( ! ids || ids.length === 0 ) {
			return __( 'No list', 'rewind-form-bridge-for-brevo' );
		}

		return ids
			.map( ( id ) => {
				const match = brevo.lists.find( ( list ) => list.id === id );

				return match ? match.name : `#${ id }`;
			} )
			.join( ', ' );
	};

	const onToggle = async ( feed ) => {
		const nextStatus = feed.status === 'active' ? 'paused' : 'active';

		setBusyId( feed.id );

		try {
			const updated = await updateFeed( feed.id, {
				title: feed.title,
				adapter: feed.adapter,
				form_id: feed.form_id,
				status: nextStatus,
				config: feed.config,
			} );

			setFeeds( ( current ) =>
				current.map( ( row ) => ( row.id === feed.id ? updated : row ) )
			);
			addToast(
				nextStatus === 'active'
					? __( 'Mapping enabled.', 'rewind-form-bridge-for-brevo' )
					: __( 'Mapping paused.', 'rewind-form-bridge-for-brevo' )
			);
		} catch ( requestError ) {
			addToast( requestError.message, 'error' );
		} finally {
			setBusyId( 0 );
		}
	};

	const onDuplicate = async ( feed ) => {
		setBusyId( feed.id );

		try {
			const copy = await duplicateFeed( feed.id );

			setFeeds( ( current ) => [ copy, ...current ] );
			addToast(
				__(
					'Mapping duplicated, and left paused so you can check it.',
					'rewind-form-bridge-for-brevo'
				)
			);
		} catch ( requestError ) {
			addToast( requestError.message, 'error' );
		} finally {
			setBusyId( 0 );
		}
	};

	const onDelete = async () => {
		const feed = pendingDelete;

		setBusyId( feed.id );

		try {
			await deleteFeed( feed.id );

			setFeeds( ( current ) =>
				current.filter( ( row ) => row.id !== feed.id )
			);
			setPendingDelete( null );
			addToast(
				__(
					'Mapping deleted. Its log entries were kept.',
					'rewind-form-bridge-for-brevo'
				)
			);
		} catch ( requestError ) {
			addToast( requestError.message, 'error' );
		} finally {
			setBusyId( 0 );
		}
	};

	return (
		<div className="rbfb-page rbfb-page--wide">
			<BlockStack gap={ 20 }>
				{ error && (
					<Note type="error">
						<Note.Normal>{ error }</Note.Normal>
					</Note>
				) }

				<Section
					icon="automation"
					title={ __(
						'Form mappings',
						'rewind-form-bridge-for-brevo'
					) }
					actions={
						<Button
							variant="primary"
							size="small"
							startIcon="add"
							onClick={ () => navigate( '/mappings/new' ) }
						>
							{ __(
								'Add mapping',
								'rewind-form-bridge-for-brevo'
							) }
						</Button>
					}
				>
					{ loading && (
						<BlockStack gap={ 10 } style={ { width: '100%' } }>
							{ [ 0, 1, 2 ].map( ( row ) => (
								<SkeletonLoader
									key={ row }
									width="100%"
									height="38px"
								/>
							) ) }
						</BlockStack>
					) }

					{ ! loading && feeds.length === 0 && (
						<EmptyState
							icon={
								<Icon
									name="automation"
									fontSize="4xl"
									color="gray-400"
								/>
							}
							title={ __(
								'No mappings yet',
								'rewind-form-bridge-for-brevo'
							) }
							description={ __(
								'A mapping connects one of your forms to a Brevo list and decides which fields travel with it.',
								'rewind-form-bridge-for-brevo'
							) }
						>
							<Button
								startIcon="add"
								variant="primary"
								size="small"
								onClick={ () => navigate( '/mappings/new' ) }
							>
								{ __(
									'Add your first mapping',
									'rewind-form-bridge-for-brevo'
								) }
							</Button>
						</EmptyState>
					) }

					{ ! loading && feeds.length > 0 && (
						<table className="rbfb-table">
							<thead>
								<tr>
									<th>
										{ __(
											'Mapping',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'Source',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'Brevo lists',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'Enabled',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th>
										{ __(
											'Last sync',
											'rewind-form-bridge-for-brevo'
										) }
									</th>
									<th />
								</tr>
							</thead>
							<tbody>
								{ feeds.map( ( feed ) => (
									<tr key={ feed.id }>
										<td>
											<InlineStack
												gap={ 8 }
												blockAlign="center"
											>
												<Text size="sm" weight="medium">
													{ feed.title }
												</Text>
												{ ! feed.available && (
													<StatusBadge status="paused" />
												) }
											</InlineStack>
										</td>
										<td>{ feed.adapter_label }</td>
										<td>
											{ listNames( feed.config?.lists ) }
										</td>
										<td>
											<Switcher
												checked={
													feed.status === 'active'
												}
												disabled={ busyId === feed.id }
												ariaLabel={ sprintf(
													/* translators: %s: mapping title. */
													__(
														'Enable %s',
														'rewind-form-bridge-for-brevo'
													),
													feed.title
												) }
												onChange={ () =>
													onToggle( feed )
												}
											/>
										</td>
										<td>
											{ formatRelative( feed.last_sync ) }
										</td>
										<td>
											<div className="rbfb-table__actions">
												<Button
													startIcon="edit"
													variant="outlined"
													size="small"
													onClick={ () =>
														navigate(
															`/mappings/${ feed.id }`
														)
													}
												>
													{ __(
														'Edit',
														'rewind-form-bridge-for-brevo'
													) }
												</Button>
												<Button
													startIcon="content_copy"
													variant="outlined"
													size="small"
													disabled={
														busyId === feed.id
													}
													onClick={ () =>
														onDuplicate( feed )
													}
												>
													{ __(
														'Duplicate',
														'rewind-form-bridge-for-brevo'
													) }
												</Button>
												<Button
													startIcon="delete"
													variant="error"
													size="small"
													onClick={ () =>
														setPendingDelete( feed )
													}
												>
													{ __(
														'Delete',
														'rewind-form-bridge-for-brevo'
													) }
												</Button>
											</div>
										</td>
									</tr>
								) ) }
							</tbody>
						</table>
					) }
				</Section>
			</BlockStack>

			{ pendingDelete && (
				<Dialog
					title={ __(
						'Delete this mapping?',
						'rewind-form-bridge-for-brevo'
					) }
					onRequestClose={ () => setPendingDelete( null ) }
				>
					<Text size="sm">
						{ sprintf(
							/* translators: %s: mapping title. */
							__(
								'"%s" will stop sending submissions to Brevo. Its delivery log entries are kept as history.',
								'rewind-form-bridge-for-brevo'
							),
							pendingDelete.title
						) }
					</Text>

					<InlineStack
						gap={ 8 }
						align="end"
						style={ { marginTop: 24 } }
					>
						<Button
							startIcon="close"
							variant="outlined"
							size="small"
							onClick={ () => setPendingDelete( null ) }
						>
							{ __( 'Cancel', 'rewind-form-bridge-for-brevo' ) }
						</Button>
						<Button
							startIcon="delete"
							variant="error"
							size="small"
							loading={ busyId === pendingDelete.id }
							disabled={ busyId === pendingDelete.id }
							onClick={ onDelete }
						>
							{ __(
								'Delete mapping',
								'rewind-form-bridge-for-brevo'
							) }
						</Button>
					</InlineStack>
				</Dialog>
			) }
		</div>
	);
}
