import React, { useEffect, useMemo, useState } from 'react';
import { ActionIcon, Alert, Badge, Button, Code, CopyButton, Divider, Group, Paper, PasswordInput, Stack, Text, TextInput } from '@mantine/core';
import { IconAlertTriangle, IconCheck, IconCopy, IconKey, IconShieldCheck, IconTrash, IconX } from '@tabler/icons-react';
import { __ } from '@wordpress/i18n';

const apiFetch = window.wp.apiFetch;

export default function WebhookTab({ settingsData, loading, onSettingsChanged }) {
	const [settings, setSettings] = useState({ webhookUsername: '', webhookPassword: '', hmacKey: '' });
	const [saving, setSaving] = useState(false);
	const [success, setSuccess] = useState(null);
	const [error, setError] = useState(null);

	useEffect(() => {
		if (!settingsData) {
			return;
		}
		setSettings({
			webhookUsername: settingsData.webhookUsername || '',
			webhookPassword: '',
			hmacKey: '',
		});
	}, [settingsData]);

	const webhookUrl = settingsData?.webhookToken
		? `${DigitalAppsPaymentsForAdyenSettings.root}webhook/${settingsData.webhookToken}`
		: '';

	const basicAuthError = useMemo(() => {
		const username = settings.webhookUsername.trim();
		const hasPassword = settings.webhookPassword !== '' || Boolean(settingsData?.webhookPasswordConfigured);
		if ((username === '') !== !hasPassword) {
			return __('Basic Auth requires both a username and a password.', 'digital-apps-payments-for-adyen');
		}
		return null;
	}, [settings, settingsData]);

	const hmacError = settings.hmacKey && !/^[a-fA-F0-9]{64}$/.test(settings.hmacKey.trim())
		? __('HMAC key must be the 64-character hexadecimal key generated by Adyen.', 'digital-apps-payments-for-adyen')
		: null;

	const applyResult = (result, message) => {
		onSettingsChanged(result.settings);
		setSettings((current) => ({ ...current, webhookPassword: '', hmacKey: '' }));
		setSuccess(message);
	};

	const sendUpdate = (data, message) => {
		setSaving(true);
		setSuccess(null);
		setError(null);
		return apiFetch({
			path: '/digitalapps-payments-for-adyen/v1/settings',
			method: 'POST',
			headers: { 'X-WP-Nonce': DigitalAppsPaymentsForAdyenSettings.nonce },
			data,
		})
			.then((result) => applyResult(result, message))
			.catch((requestError) => setError(requestError.message || __('Webhook settings could not be saved.', 'digital-apps-payments-for-adyen')))
			.finally(() => setSaving(false));
	};

	const save = (event) => {
		event.preventDefault();
		if (basicAuthError || hmacError) {
			setError(basicAuthError || hmacError);
			return;
		}
		sendUpdate(settings, __('Webhook security settings saved.', 'digital-apps-payments-for-adyen'));
	};

	const removeBasicAuth = () => sendUpdate(
		{ webhookUsername: '', clearWebhookPassword: true },
		__('Basic Auth removed.', 'digital-apps-payments-for-adyen')
	);

	const removeHmac = () => sendUpdate(
		{ clearHmacKey: true },
		__('HMAC key removed. Webhook notifications will be rejected until a new key is configured.', 'digital-apps-payments-for-adyen')
	);

	return (
		<Stack gap="md">
			{success && <Alert icon={<IconCheck size={16} />} color="green" title={__('Saved', 'digital-apps-payments-for-adyen')}>{success}</Alert>}
			{error && <Alert icon={<IconX size={16} />} color="red" title={__('Check webhook settings', 'digital-apps-payments-for-adyen')}>{error}</Alert>}

			<Alert
				icon={settingsData?.hmacKeyConfigured ? <IconShieldCheck size={18} /> : <IconAlertTriangle size={18} />}
				title={settingsData?.hmacKeyConfigured ? __('Webhook verification is ready', 'digital-apps-payments-for-adyen') : __('Webhook verification is not configured', 'digital-apps-payments-for-adyen')}
				color={settingsData?.hmacKeyConfigured ? 'green' : 'orange'}
			>
				{settingsData?.hmacKeyConfigured
					? __('Incoming notifications must match the private URL token, their Test or Live environment, and a valid current or rotation-overlap HMAC signature.', 'digital-apps-payments-for-adyen')
					: __('You can save this test setup now, but the endpoint rejects all notifications until an HMAC key is configured.', 'digital-apps-payments-for-adyen')}
			</Alert>

			<Paper p="md" withBorder>
				<Stack gap="md">
					<Group justify="space-between">
						<Text size="lg" fw={500}>{__('1. Private webhook endpoint', 'digital-apps-payments-for-adyen')}</Text>
						<Badge color={webhookUrl ? 'green' : 'gray'} variant="light">
							{webhookUrl ? __('Generated', 'digital-apps-payments-for-adyen') : __('Unavailable', 'digital-apps-payments-for-adyen')}
						</Badge>
					</Group>
					<Text size="sm" c="dimmed">
						{__('Add this URL as a Standard webhook in the Adyen Customer Area. Treat it as a secret because it contains an unguessable token.', 'digital-apps-payments-for-adyen')}
					</Text>
					<Group gap="xs" wrap="nowrap" align="stretch">
						<Code block className="digitalappsWebhookUrl">{webhookUrl || __('Save settings to generate the endpoint.', 'digital-apps-payments-for-adyen')}</Code>
						<CopyButton value={webhookUrl}>
							{({ copied, copy }) => (
								<ActionIcon
									aria-label={copied ? __('Webhook URL copied', 'digital-apps-payments-for-adyen') : __('Copy webhook URL', 'digital-apps-payments-for-adyen')}
									color={copied ? 'teal' : 'blue'}
									onClick={copy}
									variant="filled"
									disabled={!webhookUrl}
								>
									{copied ? <IconCheck size={16} /> : <IconCopy size={16} />}
								</ActionIcon>
							)}
						</CopyButton>
					</Group>
				</Stack>
			</Paper>

			<Paper component="form" onSubmit={save} p="md" withBorder noValidate>
				<Stack gap="md">
					<Group justify="space-between">
						<Text size="lg" fw={500}>{__('2. Signature verification', 'digital-apps-payments-for-adyen')}</Text>
						<Badge color={settingsData?.hmacKeyConfigured ? 'green' : 'orange'} variant="light">
							{settingsData?.hmacKeyConfigured ? __('Configured', 'digital-apps-payments-for-adyen') : __('Not configured', 'digital-apps-payments-for-adyen')}
						</Badge>
					</Group>
					<PasswordInput
						label={settingsData?.hmacKeyConfigured ? __('Replace HMAC key', 'digital-apps-payments-for-adyen') : __('HMAC key', 'digital-apps-payments-for-adyen')}
						description={__('Paste the HMAC key generated for this Standard webhook in Adyen.', 'digital-apps-payments-for-adyen')}
						placeholder={settingsData?.hmacKeyConfigured ? __('HMAC key configured - leave blank to keep it', 'digital-apps-payments-for-adyen') : __('Enter the 64-character HMAC key', 'digital-apps-payments-for-adyen')}
						value={settings.hmacKey}
						onChange={(event) => setSettings({ ...settings, hmacKey: event.currentTarget.value })}
						error={hmacError}
						disabled={loading || saving}
						visibilityToggleButtonProps={{ 'aria-label': __('Toggle HMAC key visibility', 'digital-apps-payments-for-adyen') }}
					/>
					{settingsData?.previousHmacKeyConfigured && (
						<Text size="sm" c="dimmed">
							{__('The previous key is retained temporarily for safe HMAC rotation. Removing the current key removes both keys for this environment.', 'digital-apps-payments-for-adyen')}
						</Text>
					)}
					{settingsData?.hmacKeyConfigured && (
						<Group justify="flex-end">
							<Button type="button" color="red" variant="subtle" leftSection={<IconTrash size={15} />} onClick={removeHmac} disabled={saving}>
								{__('Remove HMAC key', 'digital-apps-payments-for-adyen')}
							</Button>
						</Group>
					)}

					<Divider label={__('Optional additional layer', 'digital-apps-payments-for-adyen')} labelPosition="center" />
					<Group justify="space-between">
						<Group gap="xs"><IconKey size={17} /><Text fw={500}>{__('Basic Auth', 'digital-apps-payments-for-adyen')}</Text></Group>
						<Badge color={settingsData?.webhookPasswordConfigured ? 'green' : 'gray'} variant="light">
							{settingsData?.webhookPasswordConfigured ? __('Configured', 'digital-apps-payments-for-adyen') : __('Optional', 'digital-apps-payments-for-adyen')}
						</Badge>
					</Group>
					<TextInput
						label={__('Username', 'digital-apps-payments-for-adyen')}
						placeholder="webhook_user"
						value={settings.webhookUsername}
						onChange={(event) => setSettings({ ...settings, webhookUsername: event.currentTarget.value })}
						disabled={loading || saving}
					/>
					<PasswordInput
						label={settingsData?.webhookPasswordConfigured ? __('Replace password', 'digital-apps-payments-for-adyen') : __('Password', 'digital-apps-payments-for-adyen')}
						placeholder={settingsData?.webhookPasswordConfigured ? __('Password configured - leave blank to keep it', 'digital-apps-payments-for-adyen') : __('Enter a password', 'digital-apps-payments-for-adyen')}
						value={settings.webhookPassword}
						onChange={(event) => setSettings({ ...settings, webhookPassword: event.currentTarget.value })}
						error={basicAuthError}
						disabled={loading || saving}
						visibilityToggleButtonProps={{ 'aria-label': __('Toggle webhook password visibility', 'digital-apps-payments-for-adyen') }}
					/>
					<Group justify="space-between">
						{settingsData?.webhookPasswordConfigured ? (
							<Button type="button" color="red" variant="subtle" leftSection={<IconTrash size={15} />} onClick={removeBasicAuth} disabled={saving}>
								{__('Remove Basic Auth', 'digital-apps-payments-for-adyen')}
							</Button>
						) : <span />}
						<Button type="submit" loading={saving} disabled={loading || Boolean(basicAuthError || hmacError)}>
							{__('Save webhook security', 'digital-apps-payments-for-adyen')}
						</Button>
					</Group>
				</Stack>
			</Paper>

			<Paper p="md" withBorder>
				<Text size="lg" fw={500} mb="sm">{__('Adyen setup checklist', 'digital-apps-payments-for-adyen')}</Text>
				<ol className="digitalappsSetupList">
					<li>{__('Create or open a Standard webhook in Developers > Webhooks.', 'digital-apps-payments-for-adyen')}</li>
					<li>{__('Paste the private endpoint URL and add the same Basic Auth credentials if enabled here.', 'digital-apps-payments-for-adyen')}</li>
					<li>{__('Generate an HMAC key in Adyen, paste it above, and save.', 'digital-apps-payments-for-adyen')}</li>
					<li>{__('Use Adyen’s Test configuration action and confirm the notification is accepted.', 'digital-apps-payments-for-adyen')}</li>
				</ol>
			</Paper>
		</Stack>
	);
}
