/**
 * Connections: the API key, the resolved account, and the cached Brevo data
 * the mapping editor depends on.
 *
 * The key field is write-only. What is already stored is shown as a masked
 * hint; the input starts empty and an empty submit means "keep the key".
 */
import { useEffect, useState } from '@wordpress/element';
import Dialog from '../../components/Dialog';
import { __, sprintf } from '@wordpress/i18n';

import {
	BlockStack,
	InlineStack,
	Note,
	SkeletonLoader,
} from '../../ui/molecules';
import { Button, Input, Text } from '../../ui/atoms';
import Section from '../../components/Section';
import { refreshFromBrevo, testConnection } from '../../api/brevo';
import { saveSettings } from '../../api/settings';
import { useApp } from '../../store/AppStore';
import { formatDateTime } from '../../utils/format';

export default function Connections() {
	const {
		bootstrap,
		connection,
		setConnection,
		brevo,
		setBrevo,
		brevoState,
		loadBrevo,
		addToast,
		reloadSettings,
	} = useApp();

	const [ keyInput, setKeyInput ] = useState( '' );
	const [ revealed, setRevealed ] = useState( false );
	const [ saving, setSaving ] = useState( false );
	const [ testing, setTesting ] = useState( false );
	const [ refreshing, setRefreshing ] = useState( false );
	const [ account, setAccount ] = useState( null );
	const [ confirmDisconnect, setConfirmDisconnect ] = useState( false );

	const isConstant = connection.source === 'constant';

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

	const onSaveKey = async () => {
		if ( ! keyInput.trim() ) {
			addToast(
				__( 'Paste an API key first.', 'rewind-form-bridge-for-brevo' ),
				'error'
			);
			return;
		}

		setSaving( true );

		try {
			await saveSettings( { api_key: keyInput.trim() } );
			await reloadSettings();

			setKeyInput( '' );
			setRevealed( false );
			addToast( __( 'API key saved.', 'rewind-form-bridge-for-brevo' ) );
		} catch ( error ) {
			addToast( error.message, 'error' );
		} finally {
			setSaving( false );
		}
	};

	const onTest = async () => {
		setTesting( true );

		try {
			const result = await testConnection();

			setAccount( result );
			setConnection( ( current ) => ( {
				...current,
				hasKey: true,
				lastVerified: result.verified_at,
			} ) );
			addToast(
				__( 'Connection confirmed.', 'rewind-form-bridge-for-brevo' )
			);
		} catch ( error ) {
			setAccount( null );
			addToast( error.message, 'error' );
		} finally {
			setTesting( false );
		}
	};

	const onRefresh = async () => {
		setRefreshing( true );

		try {
			const result = await refreshFromBrevo();

			setBrevo( {
				lists: result.lists || [],
				attributes: result.attributes || [],
				cached: true,
				cachedAt: result.cached_at,
			} );

			addToast(
				sprintf(
					/* translators: 1: number of lists, 2: number of attributes. */
					__(
						'Refreshed: %1$d lists and %2$d attributes cached.',
						'rewind-form-bridge-for-brevo'
					),
					result.lists.length,
					result.attributes.length
				)
			);
		} catch ( error ) {
			addToast( error.message, 'error' );
		} finally {
			setRefreshing( false );
		}
	};

	const onDisconnect = async () => {
		setSaving( true );

		try {
			await saveSettings( { clear_api_key: true } );
			await reloadSettings();

			setAccount( null );
			setConfirmDisconnect( false );
			addToast(
				__( 'API key removed.', 'rewind-form-bridge-for-brevo' )
			);
		} catch ( error ) {
			addToast( error.message, 'error' );
		} finally {
			setSaving( false );
		}
	};

	return (
		<div className="rbfb-page rbfb-page--wide">
			<BlockStack gap={ 20 }>
				<Section
					title={ __(
						'Brevo API key',
						'rewind-form-bridge-for-brevo'
					) }
					icon="key"
					actions={
						<InlineStack gap={ 8 }>
							<Button
								variant="outlined"
								size="small"
								startIcon="refresh"
								loading={ testing }
								disabled={ testing }
								onClick={ onTest }
							>
								{ __(
									'Test connection',
									'rewind-form-bridge-for-brevo'
								) }
							</Button>

							{ connection.hasKey && ! isConstant && (
								<Button
									variant="error"
									size="small"
									startIcon="link_off"
									onClick={ () =>
										setConfirmDisconnect( true )
									}
								>
									{ __(
										'Disconnect',
										'rewind-form-bridge-for-brevo'
									) }
								</Button>
							) }
						</InlineStack>
					}
				>
					<Note type="info">
						<Note.Normal>
							{ __(
								'Brevo API keys are account-wide — they cannot be scoped to a single list or permission. Store this key only on sites you control.',
								'rewind-form-bridge-for-brevo'
							) }
						</Note.Normal>
					</Note>

					{ isConstant ? (
						<BlockStack gap={ 8 }>
							<div className="rbfb-key-row">
								<code>{ connection.hint }</code>
							</div>
							<Text size="xs" color="gray-500">
								{ __(
									'This key comes from the RBFB_API_KEY constant in wp-config.php, which overrides anything saved here. Remove the constant to manage the key from this screen.',
									'rewind-form-bridge-for-brevo'
								) }
							</Text>
						</BlockStack>
					) : (
						<BlockStack
							gap={ 12 }
							style={ { width: '100%', maxWidth: 520 } }
						>
							{ connection.hasKey && (
								<div className="rbfb-key-row">
									<code>{ connection.hint }</code>
									<Text size="xs" color="gray-500">
										{ __(
											'Only the last four characters ever reach the browser.',
											'rewind-form-bridge-for-brevo'
										) }
									</Text>
								</div>
							) }

							<Input
								label={
									connection.hasKey
										? __(
												'Replace key',
												'rewind-form-bridge-for-brevo'
										  )
										: __(
												'API key',
												'rewind-form-bridge-for-brevo'
										  )
								}
								type={ revealed ? 'text' : 'password' }
								value={ keyInput }
								onChange={ setKeyInput }
								placeholder="xkeysib-…"
								helperText={ __(
									'Create a key under SMTP & API in your Brevo account.',
									'rewind-form-bridge-for-brevo'
								) }
							/>

							<InlineStack gap={ 8 }>
								<Button
									variant="primary"
									size="small"
									startIcon="save"
									loading={ saving }
									disabled={ saving }
									onClick={ onSaveKey }
								>
									{ __(
										'Save key',
										'rewind-form-bridge-for-brevo'
									) }
								</Button>

								<Button
									variant="outlined"
									size="small"
									startIcon={
										revealed
											? 'visibility_off'
											: 'visibility'
									}
									onClick={ () =>
										setRevealed( ( value ) => ! value )
									}
								>
									{ revealed
										? __(
												'Hide',
												'rewind-form-bridge-for-brevo'
										  )
										: __(
												'Reveal',
												'rewind-form-bridge-for-brevo'
										  ) }
								</Button>

								<Button
									variant="link"
									size="small"
									endIcon="open_in_new"
									href={ bootstrap.brevoKeyUrl }
									target="_blank"
								>
									{ __(
										'Open Brevo',
										'rewind-form-bridge-for-brevo'
									) }
								</Button>
							</InlineStack>
						</BlockStack>
					) }
				</Section>

				{ account && (
					<Section
						title={ __(
							'Account',
							'rewind-form-bridge-for-brevo'
						) }
						icon="account_circle"
					>
						<InlineStack gap={ 40 } blockAlign="start">
							<BlockStack gap={ 6 }>
								<Text size="xs" color="gray-500">
									{ __(
										'Company',
										'rewind-form-bridge-for-brevo'
									) }
								</Text>
								<Text size="sm">{ account.company }</Text>
							</BlockStack>

							{ account.email && (
								<BlockStack gap={ 6 }>
									<Text size="xs" color="gray-500">
										{ __(
											'Account email',
											'rewind-form-bridge-for-brevo'
										) }
									</Text>
									<Text size="sm">{ account.email }</Text>
								</BlockStack>
							) }

							{ account.plan && (
								<BlockStack gap={ 6 }>
									<Text size="xs" color="gray-500">
										{ __(
											'Plan',
											'rewind-form-bridge-for-brevo'
										) }
									</Text>
									<Text size="sm">{ account.plan }</Text>
								</BlockStack>
							) }

							<BlockStack gap={ 6 }>
								<Text size="xs" color="gray-500">
									{ __(
										'Verified',
										'rewind-form-bridge-for-brevo'
									) }
								</Text>
								<Text size="sm">
									{ formatDateTime( account.verified_at ) }
								</Text>
							</BlockStack>
						</InlineStack>
					</Section>
				) }

				<Section
					title={ __(
						'Cached Brevo data',
						'rewind-form-bridge-for-brevo'
					) }
					icon="database"
					actions={
						<Button
							variant="outlined"
							size="small"
							startIcon="cached"
							loading={ refreshing }
							disabled={ refreshing || ! connection.hasKey }
							onClick={ onRefresh }
						>
							{ __(
								'Refresh from Brevo',
								'rewind-form-bridge-for-brevo'
							) }
						</Button>
					}
				>
					<Text size="xs" color="gray-500">
						{ __(
							'Lists and contact attributes are cached for 15 minutes so admin screens never call Brevo on their own.',
							'rewind-form-bridge-for-brevo'
						) }
					</Text>

					{ brevoState === 'loading' && (
						<SkeletonLoader width="100%" height="60px" />
					) }

					{ brevoState !== 'loading' && ! brevo.cached && (
						<Note type="warning">
							<Note.Normal>
								{ connection.hasKey
									? __(
											'Nothing is cached yet. Pull your lists and attributes once so the mapping editor has something to offer.',
											'rewind-form-bridge-for-brevo'
									  )
									: __(
											'Save an API key first, then refresh to pull your lists and attributes.',
											'rewind-form-bridge-for-brevo'
									  ) }
							</Note.Normal>
						</Note>
					) }

					{ brevoState !== 'loading' &&
						brevo.cached &&
						brevo.lists.length === 0 && (
							<Note type="warning">
								<Note.Normal>
									{ __(
										'The refresh worked, but your Brevo account has no contact lists. Create one in Brevo under Contacts → Lists, then refresh again — a mapping needs a list to subscribe contacts to.',
										'rewind-form-bridge-for-brevo'
									) }
								</Note.Normal>
							</Note>
						) }

					{ brevoState !== 'loading' && brevo.cached && (
						<InlineStack gap={ 40 } blockAlign="start">
							<BlockStack gap={ 6 }>
								<Text size="xs" color="gray-500">
									{ __(
										'Lists',
										'rewind-form-bridge-for-brevo'
									) }
								</Text>
								<Text size="sm">{ brevo.lists.length }</Text>
							</BlockStack>

							<BlockStack gap={ 6 }>
								<Text size="xs" color="gray-500">
									{ __(
										'Contact attributes',
										'rewind-form-bridge-for-brevo'
									) }
								</Text>
								<Text size="sm">
									{ brevo.attributes.length }
								</Text>
							</BlockStack>

							<BlockStack gap={ 6 }>
								<Text size="xs" color="gray-500">
									{ __(
										'Cached at',
										'rewind-form-bridge-for-brevo'
									) }
								</Text>
								<Text size="sm">
									{ formatDateTime( brevo.cachedAt ) }
								</Text>
							</BlockStack>
						</InlineStack>
					) }
				</Section>
			</BlockStack>

			{ confirmDisconnect && (
				<Dialog
					title={ __(
						'Remove the API key?',
						'rewind-form-bridge-for-brevo'
					) }
					onRequestClose={ () => setConfirmDisconnect( false ) }
				>
					<Text size="sm">
						{ __(
							'Form submissions will stop reaching Brevo until a new key is saved. Your mappings and delivery log are kept.',
							'rewind-form-bridge-for-brevo'
						) }
					</Text>

					<InlineStack
						gap={ 8 }
						align="end"
						style={ { marginTop: 24 } }
					>
						<Button
							variant="outlined"
							size="small"
							startIcon="close"
							onClick={ () => setConfirmDisconnect( false ) }
						>
							{ __( 'Cancel', 'rewind-form-bridge-for-brevo' ) }
						</Button>
						<Button
							variant="error"
							size="small"
							startIcon="delete"
							loading={ saving }
							disabled={ saving }
							onClick={ onDisconnect }
						>
							{ __(
								'Remove key',
								'rewind-form-bridge-for-brevo'
							) }
						</Button>
					</InlineStack>
				</Dialog>
			) }
		</div>
	);
}
