import { __, _n, sprintf } from '@wordpress/i18n';
import React, { useEffect, useState } from 'react';
import { api, moduleRunning, env } from '../api';
import { Card, Button, Badge, Notice, PageState, ScoreRing } from '../components/ui';
import Explain from '../components/Explain';

/**
 * Licence status, and nothing more.
 *
 * Two backends can be authoritative here:
 *
 *   backend.enforced === true   Freemius runs licensing. It owns the key, the
 *                               seats, the renewals and the update channel, so
 *                               this screen only reports what it says and
 *                               links to the screens that change it. No key is
 *                               entered, stored or displayed here — the SDK's
 *                               own activation form and account page do that.
 *   backend.enforced === false  Freemius is not configured on this build (an
 *                               internal or development copy). The local
 *                               serial store stays in charge so the screen is
 *                               still usable, and says plainly that it is a
 *                               development mode.
 *
 * Nothing on this screen can break the plugin: every field is optional, every
 * value may be null, and a licence problem never hides data the customer has
 * already produced.
 */

/** One label/value row of the status table. */
function Row({ label, children, hint }) {
	return (
		<div className="ars-licrow">
			<span className="ars-licrow-l">
				{label}
				{hint && <span className="ars-licrow-hint">{hint}</span>}
			</span>
			<span className="ars-licrow-v">{children}</span>
		</div>
	);
}

function FreemiusView({ backend, onReload }) {
	const licensed = !!backend.licensed;
	const connected = !!backend.connected;
	const grace = backend.graceDays;
	const expires = backend.expires ? String(backend.expires).slice(0, 10) : null;
	const sites = backend.siteLimit === null || backend.siteLimit === undefined ? 'Unlimited' : backend.siteLimit;

	const verdict = licensed
		? {
				tone: 'good',
				badge: __('Licensed', 'ai-rank-suite'),
				title: sprintf(__('%s is active on this site.', 'ai-rank-suite'), backend.plan || 'AI Rank Suite Agency'),
				why: expires
					? sprintf(__('Automatic updates are on and the licence renews on %s. Every Pro action — AI writing, the autopilot, answer simulation — is available.', 'ai-rank-suite'), expires)
					: 'Automatic updates are on and every Pro action is available.',
			}
		: grace !== null && grace !== undefined
			? {
					tone: 'warning',
					badge: sprintf(_n('Grace period · %d day left', 'Grace period · %d days left', grace, 'ai-rank-suite'), grace),
					title: __('The licence server could not be reached, so the last known good licence still applies.', 'ai-rank-suite'),
					why: __('This bridges a temporary outage on our side, not an expired licence. If it persists past the grace period, Pro actions pause — your settings, reports and published output stay exactly as they are.', 'ai-rank-suite'),
				}
			: {
					tone: 'bad',
					// These four were bare strings, so the one screen a
					// customer opens when something is wrong with their
					// licence spoke English inside a German admin.
					badge: connected
						? __('No active licence', 'ai-rank-suite')
						: __('Not activated', 'ai-rank-suite'),
					title: connected
						? __('This site is connected but has no active licence.', 'ai-rank-suite')
						: __('This site has no licence activated yet.', 'ai-rank-suite'),
					why: __('Your settings, reports, schema, redirects and everything already published keep working and stay untouched. Only new Pro actions and automatic updates are paused until a licence is active.', 'ai-rank-suite'),
				};

	return (
		<div className="grid gap-4">
			{backend.error && <Notice tone="warning">{backend.error}</Notice>}

			<div className="ars-hero">
				<div className="ars-hero-ring">
					<ScoreRing value={licensed ? 100 : 0} size={116} label={__('Licence', 'ai-rank-suite')} onLight />
				</div>
				<div className="ars-hero-body">
					<span className={`ars-hero-badge is-${verdict.tone}`}>{verdict.badge}</span>
					<h2 className="ars-hero-title">{verdict.title}</h2>
					<p className="ars-hero-why">{verdict.why}</p>
					<div className="ars-hero-actions">
						{!licensed && backend.activateUrl && (
							<a className="ars-btn ars-btn-primary" href={backend.activateUrl}>{__('Activate a licence', 'ai-rank-suite')}</a>
						)}
						{backend.manageUrl && (
							<a className={`ars-btn ${licensed ? 'ars-btn-primary' : 'ars-btn-ghost'}`} href={backend.manageUrl}>
								{licensed ? __('Manage licence and sites', 'ai-rank-suite') : __('Licence account', 'ai-rank-suite')}
							</a>
						)}
						{/*
						  * The one that actually asks Freemius. "Re-check now"
						  * below only re-reads our own answer, which is why a
						  * released version can stay invisible here for an hour
						  * while that button reports everything is fine. This
						  * forces the SDK to ask the server for the newest tag
						  * and realigns its state — the fix after a manual ZIP
						  * install, which replaces the files without the SDK's
						  * updater ever running.
						  */}
						{backend.syncUrl && (
							<a className="ars-linkbtn" href={backend.syncUrl}>{__('Check for a new version', 'ai-rank-suite')}</a>
						)}
						{/* Same tab, no arrow: this is the plugin's own upgrade
						    screen now, not an outbound link to Freemius'
						    pricing page — which does not exist until the
						    customer has opted in, and used to drop them on the
						    WordPress dashboard. */}
						{!licensed && backend.pricingUrl && (
							<a className="ars-linkbtn" href={backend.pricingUrl}>{__('See plans', 'ai-rank-suite')}</a>
						)}
						<button type="button" className="ars-linkbtn" onClick={onReload}>{__('Re-check now', 'ai-rank-suite')}</button>
					</div>
				</div>
				<div className="ars-hero-stats">
					<div className="ars-hero-stat" style={{ cursor: 'default' }}>
						<span className={`ars-hero-stat-v${licensed ? ' is-good' : ''}`}>{licensed ? 'On' : 'Off'}</span>
						<span className="ars-hero-stat-l">{__('Automatic updates', 'ai-rank-suite')}</span>
					</div>
					<div className="ars-hero-stat" style={{ cursor: 'default' }}>
						<span className="ars-hero-stat-v">{sites}</span>
						<span className="ars-hero-stat-l">{__('Sites in this plan', 'ai-rank-suite')}</span>
					</div>
				</div>
			</div>

			<Card title={__('Status', 'ai-rank-suite')} subtitle={__('What the licence server reports for this site', 'ai-rank-suite')} flush>
				<div className="ars-lictable">
					<Row label={__('Plan', 'ai-rank-suite')}>
						{backend.plan ? (
							<>
								{backend.plan}
								{backend.isTrial ? ' · trial' : ''}
							</>
						) : (
							<span className="is-muted">—</span>
						)}
					</Row>
					<Row label={__('Licence', 'ai-rank-suite')}>
						{licensed ? (
							<Badge tone="good">{__('active', 'ai-rank-suite')}</Badge>
						) : grace !== null && grace !== undefined ? (
							<Badge tone="warning">grace period</Badge>
						) : (
							<Badge tone="neutral">{__('inactive', 'ai-rank-suite')}</Badge>
						)}
						{backend.isCancelled ? <span className="ml-2 t-caption">cancelled — runs to the end of the term</span> : null}
					</Row>
					<Row label={__('This site', 'ai-rank-suite')} hint={__('A seat is used per site, and freed when you deactivate it', 'ai-rank-suite')}>
						{backend.siteActive ? <Badge tone="good">{__('activated', 'ai-rank-suite')}</Badge> : <Badge tone="neutral">{__('not activated', 'ai-rank-suite')}</Badge>}
						{backend.sites !== null && backend.sites !== undefined ? (
							<span className="ml-2 t-caption">
								{backend.sites} {backend.sites === 1 ? 'site' : 'sites'} using this licence
								{backend.siteLimit ? ' ' + sprintf(__('of %s', 'ai-rank-suite'), backend.siteLimit) : ' · ' + __('unlimited', 'ai-rank-suite')}
							</span>
						) : null}
					</Row>
					<Row label={__('Renews', 'ai-rank-suite')}>{expires || <span className="is-muted">—</span>}</Row>
					<Row label={__('Automatic updates', 'ai-rank-suite')}>
						{backend.updates ? <Badge tone="good">{__('enabled', 'ai-rank-suite')}</Badge> : <Badge tone="neutral">{__('paused', 'ai-rank-suite')}</Badge>}
					</Row>
					<Row label={__('Licence server', 'ai-rank-suite')}>
						{connected ? <Badge tone="good">{__('connected', 'ai-rank-suite')}</Badge> : <Badge tone="neutral">{__('not connected', 'ai-rank-suite')}</Badge>}
						{backend.userEmail ? <span className="ml-2 t-caption">{backend.userEmail}</span> : null}
					</Row>
					{(backend.productId || backend.slug) && (
						<Row label={__('Product', 'ai-rank-suite')}>
							<span className="ars-mono text-[12px]">
								{[backend.productId ? `#${backend.productId}` : '', backend.slug || '']
									.filter(Boolean)
									.join(' · ')}
								{backend.sdkVersion ? ` · SDK ${backend.sdkVersion}` : ''}
							</span>
						</Row>
					)}
				</div>
			</Card>

			<Card title={__('What an inactive licence does and does not do', 'ai-rank-suite')}>
				<div className="grid gap-3">
					<div className="grid gap-2 md:grid-cols-2">
						<div className="ars-r-md px-3 py-2.5" style={{ background: 'var(--ars-surface-2)' }}>
							<div className="font-semibold text-[13px]" style={{ color: 'var(--ars-good)' }}>{__('Keeps working', 'ai-rank-suite')}</div>
							<div className="t-caption mt-1">
								{__('Every published title, description, schema block, redirect, llms.txt and sitemap. All settings, scores, audits and reports. Nothing is deleted, hidden or switched off on the front end — a licence problem must never cost you rankings.', 'ai-rank-suite')}
							</div>
						</div>
						<div className="ars-r-md px-3 py-2.5" style={{ background: 'var(--ars-surface-2)' }}>
							<div className="font-semibold text-[13px]" style={{ color: 'var(--ars-accent)' }}>{__('Pauses', 'ai-rank-suite')}</div>
							<div className="t-caption mt-1">
								{__('New Pro actions — AI writing, the autopilot, answer simulation, keyword ideas — and automatic updates. They resume the moment a licence is active again.', 'ai-rank-suite')}
							</div>
						</div>
					</div>
					<Explain title={__('Where licences are managed', 'ai-rank-suite')}>
						<p>
							Your licence key, seats, invoices and renewals live in your account with our licensing provider
							(Freemius). This screen reads that state and links to it; it never stores a key of its own and never
							asks you to paste one anywhere else. Use <strong>{__('Manage licence and sites', 'ai-rank-suite')}</strong> to move a licence
							between sites, download invoices or cancel.
						</p>
					</Explain>
				</div>
			</Card>
		</div>
	);
}

export default function License() {
	const [state, setState] = useState(null);
	const [error, setError] = useState(null);
	// The free edition carries no licensing module at all, so there is no
	// /license route to read: the tab says what this edition is and where Pro
	// is, instead of asking a route that does not exist and showing its 404.
	const hasLicensing = moduleRunning('licensing');

	const load = () =>
		api
			.get('/license')
			.then(setState)
			.catch((e) => setError(e.message));

	useEffect(() => {
		if (hasLicensing) load();
	}, [hasLicensing]);

	if (!hasLicensing) {
		return (
			<div className="ars-page">
				<Card title={__('Free edition', 'ai-rank-suite')}>
					<div className="ars-pro is-compact">
						<span className="ars-pro-badge">{__('Pro', 'ai-rank-suite')}</span>
						<div className="min-w-0">
							<p className="ars-pro-text">
								{__('This is the free edition from WordPress.org. It has no licence to manage: every feature in it is fully yours. The AI engine, the autopilot, answer simulation, rank tracking and the other Pro modules come with AI Rank Suite Pro, sold and updated through our own site.', 'ai-rank-suite')}
							</p>
						</div>
						<a className="ars-btn ars-btn-ghost ars-pro-cta" href={`${env.adminUrl || ''}admin.php?page=ai-rank-suite-upgrade`}>{__('See Pro', 'ai-rank-suite')}</a>
					</div>
				</Card>
			</div>
		);
	}

	if (!state) return <PageState error={error} />;

	// There is nothing to type here and nothing to submit. Freemius owns the
	// key, the plan, the trial and the renewal; this screen reads that state
	// and links to the screens that change it. The field that used to sit here
	// asked for a serial number in a format this plugin invented, stored it
	// locally, and validated it against nothing — a customer who had just paid
	// would have been shown a box for a key that does not exist.
	const backend = state.backend || state;

	if (backend.enforced) {
		return (
			<div className="ars-page">
				{error && <Notice tone="serious">{error}</Notice>}
				<FreemiusView backend={backend} onReload={load} />
			</div>
		);
	}

	// A build whose Freemius credentials were never filled in. That is a
	// development copy, and it must not lock its own owner out: everything
	// runs, licensing simply is not switched on.
	return (
		<div className="ars-page">
			{error && <Notice tone="serious">{error}</Notice>}
			<Notice tone="info">
				<b>{__('Development build.', 'ai-rank-suite')}</b>{' '}
				{__('No licensing provider is configured, so nothing on this copy is gated. Licensing and automatic updates are switched off; every other feature works normally.', 'ai-rank-suite')}{' '}
				{__('A released build carries real credentials, and this screen then shows the licence state of the site.', 'ai-rank-suite')}
			</Notice>
			<Card
				title={__('Licensing', 'ai-rank-suite')}
				subtitle={__('Handled entirely by our licensing provider — nothing is stored here', 'ai-rank-suite')}
			>
				<p className="m-0 t-body">
					{__('Your licence key, seats, invoices, renewals and trials live in your account with Freemius. This plugin reads that state; it never keeps a key of its own, and there is nothing on this screen to fill in.', 'ai-rank-suite')}
				</p>
			</Card>
		</div>
	);
}
