import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { Alert, Button, Icon, Input } from '../../../shared/ui';
import { SummaryList, PriceLines } from './Summary';
import StripePay from './StripePay';
import { displayValue } from '../fields';
import { formatMoney } from '../format';
import { paymentMeta, stripePublishableKey } from '../payments';
import { brandTheme } from '../config';

function PromoField({ flow }) {
	const { promo } = flow;
	const [code, setCode] = useState('');
	if (!window.pointlybooking_FRONT?.promoCodes && !promo.code) return null;

	if (promo.code) {
		return (
			<div className="bp-bw-promo bp-bw-promo--applied">
				<Icon name="ticket" />
				<span>
					<strong>{promo.code}</strong> {__('applied', 'pointly-booking')}
				</span>
				<Button variant="link" size="sm" onClick={() => flow.actions.removePromo()}>
					{__('Remove', 'pointly-booking')}
				</Button>
			</div>
		);
	}

	const apply = (e) => {
		e.preventDefault();
		flow.actions.applyPromo(code);
	};

	return (
		<form className="bp-bw-promo" onSubmit={apply}>
			<label className="bp-label" htmlFor="bp-bw-promo">
				{__('Promo code', 'pointly-booking')}
			</label>
			<div className="bp-bw-promo__row">
				<Input
					id="bp-bw-promo"
					value={code}
					autoComplete="off"
					autoCapitalize="characters"
					aria-invalid={promo.error ? 'true' : undefined}
					aria-describedby={promo.error ? 'bp-bw-promo-error' : undefined}
					onChange={(e) => setCode(e.target.value)}
				/>
				<Button type="submit" variant="secondary" loading={promo.checking} disabled={!code.trim()}>
					{__('Apply', 'pointly-booking')}
				</Button>
			</div>
			{promo.error ? (
				<div id="bp-bw-promo-error" className="bp-error-text" role="alert">
					<Icon name="alert-circle" size={14} />
					<span>{promo.error}</span>
				</div>
			) : null}
		</form>
	);
}

function DetailsReview({ flow }) {
	const rows = [];
	flow.fieldGroups.forEach((g) =>
		g.items.forEach(({ key, def }) => {
			const v = flow.answers[key];
			if (v === undefined || v === null || v === '' || v === false) return;
			rows.push({ key, label: def.label || key, value: displayValue(def, v) });
		})
	);
	if (!rows.length) return null;
	return (
		<section className="bp-bw-review__block">
			<div className="bp-bw-review__head">
				<h3 className="bp-bw-subhead">{__('Your details', 'pointly-booking')}</h3>
				<Button variant="link" size="sm" onClick={() => flow.actions.goTo('customer')}>
					{__('Change', 'pointly-booking')}
				</Button>
			</div>
			<dl className="bp-bw-review__dl">
				{rows.map((r) => (
					<div key={r.key} className="bp-bw-review__row">
						<dt>{r.label}</dt>
						<dd>{r.value}</dd>
					</div>
				))}
			</dl>
		</section>
	);
}

export default function ReviewStep({ flow }) {
	const method = flow.paymentMethod;
	const meta = paymentMeta(method);
	const total = flow.pricing ? flow.pricing.total : 0;

	if (flow.pay) {
		return (
			<div className="bp-bw-review">
				<Alert tone="info">{__('Your time is being held for you while you pay.', 'pointly-booking')}</Alert>
				<StripePay
					publishableKey={stripePublishableKey()}
					clientSecret={flow.pay.clientSecret}
					bookingId={flow.pay.bookingId}
					bookingKey={flow.pay.key}
					amountLabel={flow.pricing ? formatMoney(flow.pricing.total, flow.pricing.currency) : ''}
					dark={brandTheme().dark}
					onPaid={flow.actions.cardPaid}
				/>
			</div>
		);
	}

	return (
		<div className="bp-bw-review">
			<section className="bp-bw-review__block">
				<h3 className="bp-bw-subhead">{__('Your appointment', 'pointly-booking')}</h3>
				<SummaryList flow={flow} editable />
			</section>

			<DetailsReview flow={flow} />

			<section className="bp-bw-review__block">
				{total > 0 ? (
					<div className="bp-bw-review__head">
						<h3 className="bp-bw-subhead">{__('Payment', 'pointly-booking')}</h3>
						{flow.payOpts.methods.length > 1 && flow.history.includes('payment') ? (
							<Button variant="link" size="sm" onClick={() => flow.actions.goTo('payment')}>
								{__('Change', 'pointly-booking')}
							</Button>
						) : null}
					</div>
				) : null}
				{total > 0 ? (
					<p className="bp-bw-review__method">
						<Icon name={meta.icon} />
						<span>{meta.label}</span>
					</p>
				) : null}
				<PromoField flow={flow} />
				<PriceLines flow={flow} />
			</section>

			{flow.submitError ? (
				<Alert tone="danger" live>
					{flow.submitError}
				</Alert>
			) : null}
		</div>
	);
}
