import { Alert, Button, Checkbox, Form, Radio, Typography } from 'antd';
import { __ } from '@wordpress/i18n';

export const managedPaymentsDefaults = {
	sahcfwc_managed_payments_enabled: 'no',
	sahcfwc_managed_payments_merchant_attested: 'no',
	sahcfwc_managed_payments_mixed_policy: 'block',
	sahcfwc_managed_payments_standard_fallback_opt_in: 'no',
};

export const normalizeManagedPaymentsValues = ( values ) => {
	const validEnvelope = values !== null && typeof values === 'object' && ! Array.isArray( values );
	const saved = ( key ) => validEnvelope
		? ( Object.prototype.hasOwnProperty.call( values, key ) ? values[ key ] : managedPaymentsDefaults[ key ] )
		: null;
	// Default only genuinely absent options. Preserve invalid saved values so an
	// unrelated save cannot silently turn an invalid/blocked route into standard.
	return {
		sahcfwc_managed_payments_enabled: saved( 'sahcfwc_managed_payments_enabled' ),
		sahcfwc_managed_payments_merchant_attested: saved( 'sahcfwc_managed_payments_merchant_attested' ),
		sahcfwc_managed_payments_mixed_policy: saved( 'sahcfwc_managed_payments_mixed_policy' ),
		sahcfwc_managed_payments_standard_fallback_opt_in: saved( 'sahcfwc_managed_payments_standard_fallback_opt_in' ),
	};
};

const hasValidManagedPaymentsShape = ( values ) => values
	&& [ 'yes', 'no' ].includes( values.sahcfwc_managed_payments_enabled )
	&& [ 'yes', 'no' ].includes( values.sahcfwc_managed_payments_merchant_attested )
	&& [ 'block', 'standard' ].includes( values.sahcfwc_managed_payments_mixed_policy )
	&& [ 'yes', 'no' ].includes( values.sahcfwc_managed_payments_standard_fallback_opt_in );

/** Explicit submit guard as well as field validation; never auto-check an acknowledgement. */
export const managedPaymentsValidationError = ( values ) => {
	if ( ! hasValidManagedPaymentsShape( values ) ) {
		return __( 'Review the Managed Payments configuration before saving.', 'sa-hosted-checkout-for-woocommerce' );
	}
	if ( values.sahcfwc_managed_payments_enabled !== 'yes' ) { return ''; }
	if ( values.sahcfwc_managed_payments_merchant_attested !== 'yes' ) {
		return __( 'Review and acknowledge the Managed Payments eligibility requirements before enabling this configuration.', 'sa-hosted-checkout-for-woocommerce' );
	}
	if ( values.sahcfwc_managed_payments_mixed_policy === 'standard'
		&& values.sahcfwc_managed_payments_standard_fallback_opt_in !== 'yes' ) {
		return __( 'Acknowledge your tax responsibilities before allowing whole-cart standard Stripe Checkout.', 'sa-hosted-checkout-for-woocommerce' );
	}
	return '';
};

const yesNoCheckbox = {
	getValueProps: ( value ) => ( { checked: value === 'yes' } ),
	getValueFromEvent: ( event ) => event.target.checked ? 'yes' : 'no',
};

export default function ManagedPaymentsSettings() {
	const form = Form.useFormInstance();
	const values = {
		sahcfwc_managed_payments_enabled: Form.useWatch( 'sahcfwc_managed_payments_enabled' ),
		sahcfwc_managed_payments_merchant_attested: Form.useWatch( 'sahcfwc_managed_payments_merchant_attested' ),
		sahcfwc_managed_payments_mixed_policy: Form.useWatch( 'sahcfwc_managed_payments_mixed_policy' ),
		sahcfwc_managed_payments_standard_fallback_opt_in: Form.useWatch( 'sahcfwc_managed_payments_standard_fallback_opt_in' ),
	};
	const enabled = values.sahcfwc_managed_payments_enabled === 'yes';
	const mixedPolicy = values.sahcfwc_managed_payments_mixed_policy;
	const malformed = Object.values( values ).some( ( value ) => value !== undefined ) && ! hasValidManagedPaymentsShape( values );
	return <section aria-labelledby="sahcfwc-managed-payments-title">
		<Typography.Title id="sahcfwc-managed-payments-title" level={ 4 }>
			{ __( 'Managed Payments', 'sa-hosted-checkout-for-woocommerce' ) }
		</Typography.Title>
		<Form.Item name="sahcfwc_managed_payments_enabled"
			label={ __( 'Enable Managed Payments', 'sa-hosted-checkout-for-woocommerce' ) }>
			<Radio.Group options={ [
				{ label: __( 'Disabled', 'sa-hosted-checkout-for-woocommerce' ), value: 'no' },
				{ label: __( 'Enabled', 'sa-hosted-checkout-for-woocommerce' ), value: 'yes' },
			] } />
		</Form.Item>
		<div hidden={ ! enabled } data-testid="sahcfwc-managed-payments-details">
		<Alert type="warning" showIcon
			message={ __( 'Activate Managed Payments in Stripe and configure a working webhook before enabling it here.', 'sa-hosted-checkout-for-woocommerce' ) }
			description={ __( 'One-time eligible digital products only. Quantities are fixed. Stripe controls final taxes, payment methods and currency conversion. Standard checkout shipping, quantity, branding, language and optional phone/terms settings are not applied to this Managed Payments flow. Test your configuration in a Stripe sandbox before accepting live payments.', 'sa-hosted-checkout-for-woocommerce' ) }
		/>
		<Typography.Paragraph>
			{ __( 'Configure products individually in WooCommerce. Only eligible digital products with an assigned tax category and your eligibility confirmation can use Managed Payments. Saving settings is not Stripe approval; live use also requires activation and eligibility for your Stripe account.', 'sa-hosted-checkout-for-woocommerce' ) }
		</Typography.Paragraph>
		<Typography.Paragraph>
			{ __( 'Tax coverage depends on the transaction. Managed Payments does not transfer tax responsibility to Stripe for every sale. For transactions outside its tax coverage, you remain responsible and Stripe Tax is the only supported tax calculation solution.', 'sa-hosted-checkout-for-woocommerce' ) }{ ' ' }
			<a href="https://docs.stripe.com/payments/managed-payments/tax-compliance" target="_blank" rel="noopener noreferrer">
				{ __( 'Review Stripe’s tax coverage and exceptions', 'sa-hosted-checkout-for-woocommerce' ) }
			</a>
		</Typography.Paragraph>
		</div>
		{ malformed && <Alert type="error" showIcon
			message={ __( 'The saved Managed Payments configuration contains invalid values.', 'sa-hosted-checkout-for-woocommerce' ) }
			description={ __( 'Review the configuration or explicitly reset it to disabled defaults. No changes are saved until you submit this form.', 'sa-hosted-checkout-for-woocommerce' ) }
			action={ <Button onClick={ () => form.setFieldsValue( { ...managedPaymentsDefaults } ) }>
				{ __( 'Reset to disabled defaults', 'sa-hosted-checkout-for-woocommerce' ) }
			</Button> }
		/> }
		<>
			<Form.Item name="sahcfwc_managed_payments_merchant_attested" { ...yesNoCheckbox } hidden={ ! enabled }
				rules={ [ { validator: ( _, value ) => ! enabled || value === 'yes' ? Promise.resolve() : Promise.reject( new Error( __( 'Confirm that you have reviewed the eligibility requirements.', 'sa-hosted-checkout-for-woocommerce' ) ) ) } ] }>
				<Checkbox>{ __( 'I have reviewed Stripe’s eligibility requirements and will only opt in products that meet them.', 'sa-hosted-checkout-for-woocommerce' ) }</Checkbox>
			</Form.Item>
			<Typography.Paragraph hidden={ ! enabled }>
				<a href="https://docs.stripe.com/payments/managed-payments/eligibility" target="_blank" rel="noopener noreferrer">
					{ __( 'Read Stripe’s Managed Payments eligibility requirements', 'sa-hosted-checkout-for-woocommerce' ) }
				</a>
			</Typography.Paragraph>
			<Form.Item name="sahcfwc_managed_payments_mixed_policy" hidden={ ! enabled }
				label={ __( 'Mixed or ineligible carts', 'sa-hosted-checkout-for-woocommerce' ) }>
				<Radio.Group options={ [
					{ label: __( 'Block Stripe checkout and ask the customer to adjust the cart', 'sa-hosted-checkout-for-woocommerce' ), value: 'block' },
					{ label: __( 'Use standard Stripe Checkout for the entire cart', 'sa-hosted-checkout-for-woocommerce' ), value: 'standard' },
				] } />
			</Form.Item>
			{ enabled && mixedPolicy === 'standard' &&
				<Alert type="warning" showIcon
					message={ __( 'Standard checkout does not use Managed Payments for any item in that order.', 'sa-hosted-checkout-for-woocommerce' ) }
					description={ __( 'You remain the merchant of record and are responsible for applicable taxes on the entire transaction. Your standard WooCommerce tax and shipping configuration must be suitable. The cart is not split into separate payments.', 'sa-hosted-checkout-for-woocommerce' ) }
				/>
			}
			<Form.Item name="sahcfwc_managed_payments_standard_fallback_opt_in" { ...yesNoCheckbox } hidden={ ! enabled || mixedPolicy !== 'standard' }
				rules={ [ { validator: ( _, value ) => ! enabled || mixedPolicy !== 'standard' || value === 'yes' ? Promise.resolve() : Promise.reject( new Error( __( 'Acknowledge your tax responsibilities for standard checkout.', 'sa-hosted-checkout-for-woocommerce' ) ) ) } ] }>
				<Checkbox>{ __( 'I explicitly allow the entire mixed or ineligible cart to use standard Stripe Checkout and accept the associated merchant and tax responsibilities.', 'sa-hosted-checkout-for-woocommerce' ) }</Checkbox>
			</Form.Item>
		</>
	</section>;
}
