import React, { useRef } from "react";
import { __ } from "@wordpress/i18n";
import { BILLING_PERIODS, MODE_DESCRIPTIONS, SUBSCRIPTION_MODES, normalizeSchedule } from "./schedule";
import "./subscription-schedule.scss";

/** Shared schedule controls for the box editor and the Pro bundle editor. */
const SubscriptionScheduleFields = ({ schedule, onChange, flexibleAvailable = false, prefix = "arraysubs-box", maxInterval = 12 }) => {
	const mode = flexibleAvailable ? schedule.mode || "fixed" : "fixed";
	const fullFlexible = mode === "full_flexible";
	const previousInterval = useRef(fullFlexible ? 1 : schedule.interval);
	const update = (patch) => onChange(normalizeSchedule({ ...schedule, ...patch }, maxInterval, flexibleAvailable));
	const changeMode = (nextMode) => {
		if (nextMode === mode) return;
		if (nextMode === "full_flexible") previousInterval.current = schedule.interval;
		update({ mode: nextMode, interval: nextMode === "full_flexible" ? 1 : previousInterval.current });
	};
	const selectedPeriods = schedule.flexible_periods || [schedule.period];

	return (
		<>
			<div className="arraysubs-container-schedule">
				<h4 className="arraysubs-container-schedule__title">{__("Subscription Type", "arraysubs")}</h4>
				<div className="arraysubs-container-schedule__modes" role="group" aria-label={__("Subscription type", "arraysubs")}>
					{Object.entries(SUBSCRIPTION_MODES).map(([value, label]) => (
						<button key={value} type="button" className={`button${mode === value ? " button-primary" : ""}`} aria-pressed={mode === value} disabled={value !== "fixed" && !flexibleAvailable} onClick={() => changeMode(value)}>
							{label}{value !== "fixed" && !flexibleAvailable && <span className="arraysubs-container-schedule__pro">{__("Pro", "arraysubs")}</span>}
						</button>
					))}
				</div>
				<p className={`${prefix}-field__help`}>{MODE_DESCRIPTIONS[mode]}</p>
				{fullFlexible && (
					<fieldset className="arraysubs-container-schedule__periods">
						<legend className={`${prefix}-field__label`}>{__("Available Billing Periods", "arraysubs")}</legend>
						<div className="arraysubs-container-schedule__period-options">
							{BILLING_PERIODS.map(({ value, label }) => (
								<label key={value}>
									<input type="checkbox" checked={selectedPeriods.includes(value)} disabled={selectedPeriods.length === 1 && selectedPeriods.includes(value)} onChange={(event) => update({ flexible_periods: event.target.checked ? [...selectedPeriods, value] : selectedPeriods.filter((period) => period !== value) })} />
									{label}
								</label>
							))}
						</div>
						<p className={`${prefix}-field__help`}>{__("Customers pick one of these billing periods at purchase. Choose at least one period. The billing interval is fixed at 1.", "arraysubs")}</p>
					</fieldset>
				)}
			</div>
			<div className={`${prefix}-grid-3`}>
				{!fullFlexible && <>
					<label className={`${prefix}-field`}>
						<span className={`${prefix}-field__label`}>{__("Billing Period", "arraysubs")}</span>
						<select className={`${prefix}-input`} value={schedule.period} onChange={(event) => update({ period: event.target.value })}>
							{BILLING_PERIODS.map(({ value, label }) => <option key={value} value={value}>{label}</option>)}
						</select>
					</label>
					<label className={`${prefix}-field`}>
						<span className={`${prefix}-field__label`}>{__("Billing Interval", "arraysubs")}</span>
						<input type="number" className={`${prefix}-input`} min="1" max={maxInterval} step="1" value={schedule.interval} onChange={(event) => { previousInterval.current = event.target.value; update({ interval: event.target.value }); }} />
						<span className={`${prefix}-field__help`}>{__("Charge every X periods", "arraysubs")}</span>
					</label>
				</>}
				<label className={`${prefix}-field`}>
					<span className={`${prefix}-field__label`}>{mode === "fixed" ? __("Subscription Length", "arraysubs") : __("Maximum Length", "arraysubs")}</span>
					<input type="number" className={`${prefix}-input`} min="0" max="365" step="1" value={schedule.length} onChange={(event) => update({ length: event.target.value })} />
					<span className={`${prefix}-field__help`}>{mode === "fixed" ? __("Number of billing cycles (0 = never expires)", "arraysubs") : __("Customers choose up to this many billing cycles. Use 0 for no configured maximum (up to 365 cycles per purchase).", "arraysubs")}</span>
				</label>
			</div>
		</>
	);
};

export default SubscriptionScheduleFields;
