/**
 * "More WordPress Free plugins" — core's own Plugins → Add New card markup (`.plugin-card`, `.plugin-card-top`,
 * `.plugin-card-bottom`, `wp_star_rating()`'s `.star-rating`), laid out by wp-admin's list-tables.css exactly as
 * Real Testimonials Free's Our Plugins page is: 148px icon gutter, actions pinned top-right, two cards a row
 * (three from 1600px).
 *
 * Install / Activate run over core's `wp/v2/plugins` REST route (capability checked there), so the card
 * updates in place with no page load.
 */
import apiFetch from '@wordpress/api-fetch';
import { useState } from '@wordpress/element';
import { __, _n, sprintf } from '@wordpress/i18n';
import useOurPlugins from '../hooks/useOurPlugins';

const STAR_COUNT = 5;

// wp_star_rating( type: percent ) markup — core's `.star-rating .star-*` CSS draws it.
const StarRating = ({ rating, count }) => {
	const stars = Math.round(rating / 10) / 2;
	const full = Math.floor(stars);
	const half = Math.ceil(stars - full);
	const empty = STAR_COUNT - full - half;
	const classes = [
		...Array(full).fill('star-full'),
		...Array(half).fill('star-half'),
		...Array(empty).fill('star-empty'),
	];

	return (
		<div className="star-rating">
			<span className="screen-reader-text">
				{sprintf(
					/* translators: 1: rating out of 5, 2: number of ratings */
					_n(
						'%1$s rating based on %2$s rating',
						'%1$s rating based on %2$s ratings',
						count,
						'team-free'
					),
					stars,
					count.toLocaleString()
				)}
			</span>
			{classes.map((name, index) => (
				<div key={index} className={`star ${name}`} aria-hidden="true" />
			))}
		</div>
	);
};

const Action = ({ plugin, onChange }) => {
	const [busy, setBusy] = useState(false);
	const [failed, setFailed] = useState('');

	// Many plugins (ShapedPlugin's own included) answer `activated_plugin` with `wp_safe_redirect()` + `exit` to
	// their welcome screen, so the core route returns a 302 instead of JSON even though the plugin was activated.
	// `redirect: 'manual'` stops the browser loading that screen, and the server's real state decides the outcome.
	const run = (request, expected) => {
		if (busy) {
			return;
		}
		setBusy(true);
		setFailed('');

		let requestError = null;
		request
			.catch((error) => {
				requestError = error;
			})
			.then(() => apiFetch({ path: '/sptp/v1/our-plugins' }))
			.then((response) => {
				const fresh = (response?.plugins || []).find((item) => item.slug === plugin.slug);
				if (fresh && fresh.status === expected) {
					setBusy(false);
					onChange(plugin.slug, fresh);
					return;
				}
				throw requestError || new Error('');
			})
			.catch((error) => {
				setBusy(false);
				setFailed(
					error?.message
						? error.message.replace(/<[^>]*>/g, '')
						: __('Failed. Try again.', 'team-free')
				);
			});
	};

	if ('active' === plugin.status) {
		return (
			<button type="button" className="button button-disabled" disabled>
				{__('Active', 'team-free')}
			</button>
		);
	}

	let label = '';
	let busyLabel = '';
	let handler = null;
	let primary = false;

	if ('installed' === plugin.status && plugin.canActivate && plugin.file) {
		label = __('Activate', 'team-free');
		busyLabel = __('Activating…', 'team-free');
		primary = true;
		handler = () =>
			run(
				apiFetch({
					path: `/wp/v2/plugins/${plugin.file}`,
					method: 'PUT',
					data: { status: 'active' },
					redirect: 'manual',
				}),
				'active'
			);
	} else if ('not_installed' === plugin.status && plugin.canInstall) {
		label = __('Install Now', 'team-free');
		busyLabel = __('Installing…', 'team-free');
		handler = () =>
			run(
				apiFetch({
					path: '/wp/v2/plugins',
					method: 'POST',
					data: { slug: plugin.slug, status: 'inactive' },
					redirect: 'manual',
				}),
				'installed'
			);
	}

	if (!handler) {
		return null;
	}

	return (
		<>
			<button
				type="button"
				className={`button${primary ? ' button-primary activate-now' : ' install-now'}${
					busy ? ' updating-message' : ''
				}`}
				onClick={handler}
				disabled={busy}
				aria-busy={busy}
			>
				{busy ? busyLabel : label}
			</button>
			{failed && (
				<span className="sptp-plugin-action__error" role="alert">
					{failed}
				</span>
			)}
		</>
	);
};

const OurPluginCards = () => {
	const { status, plugins, updatePlugin } = useOurPlugins();

	// The cards are the whole Our Plugins page, so loading and failure need a visible state.
	if ('loading' === status) {
		return (
			<div className="sptp-loading">
				<span className="spinner is-active" style={{ float: 'none', margin: 0 }} />
			</div>
		);
	}
	if (!plugins.length) {
		return (
			<div className="notice notice-info inline">
				<p>
					{__('The plugin list could not be loaded right now.', 'team-free')}{' '}
					<a
						href="https://profiles.wordpress.org/shapedplugin/#content-plugins"
						target="_blank"
						rel="noopener noreferrer"
					>
						{__('Browse our plugins on WordPress.org', 'team-free')}
					</a>
				</p>
			</div>
		);
	}

	return (
		<div className="sptp-our-plugins plugin-install-php">
			<h2 className="sptp-our-plugins__title">
				{__(
					'Supercharge Your Website with Our Free Plugins — Trusted by 400,200+ Users',
					'team-free'
				)}
			</h2>
			<div className="sptp-our-plugins__list">
				{plugins.map((plugin) => (
					<div key={plugin.slug} className={`plugin-card plugin-card-${plugin.slug}`}>
						<div className="plugin-card-top">
							<div className="name column-name">
								<h3>
									<a
										className="thickbox open-plugin-details-modal"
										href={plugin.detailsUrl}
										title={plugin.name}
									>
										{plugin.name}
										{plugin.icon && (
											<img className="plugin-icon" src={plugin.icon} alt="" />
										)}
									</a>
								</h3>
							</div>
							<div className="action-links">
								<ul className="plugin-action-buttons">
									<li>
										<Action plugin={plugin} onChange={updatePlugin} />
									</li>
									<li>
										<a
											className="thickbox open-plugin-details-modal"
											href={plugin.detailsUrl}
											title={plugin.name}
											aria-label={sprintf(
												/* translators: %s: plugin name */
												__('More information about %s', 'team-free'),
												plugin.name
											)}
										>
											{__('More Details', 'team-free')}
										</a>
									</li>
								</ul>
							</div>
							<div className="desc column-description">
								<p>{plugin.description}</p>
							</div>
						</div>
						<div className="plugin-card-bottom">
							<div className="vers column-rating">
								<StarRating rating={plugin.rating} count={plugin.numRatings} />
								<span className="num-ratings" aria-hidden="true">
									({plugin.numRatings.toLocaleString()})
								</span>
							</div>
							{plugin.version && (
								<div className="column-updated">
									<strong>{__('Version:', 'team-free')}</strong>{' '}
									<span>{plugin.version}</span>
								</div>
							)}
							{plugin.activeInstallsLabel && (
								<div className="column-downloaded">
									{plugin.activeInstallsLabel}
								</div>
							)}
							{plugin.lastUpdatedLabel && (
								<div className="column-compatibility">
									<strong>{__('Last Updated:', 'team-free')}</strong>{' '}
									<span>{plugin.lastUpdatedLabel}</span>
								</div>
							)}
						</div>
					</div>
				))}
			</div>
		</div>
	);
};

export default OurPluginCards;
