import React, { useEffect, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import FirstRun from '../components/FirstRun';
import ScreenVerdict from '../components/ScreenVerdict';
import { Card, Button, Badge, Notice, MetricGrid, Gauge, PageState } from '../components/ui';
import { IconRefresh, IconShield } from '../components/icons';

/**
 * Site-wide technical tests.
 *
 * The page audit answers "which of my pages have problems". These answer "is
 * this site set up correctly at all" — faults that belong to no page and so
 * appear in no page report, while quietly defeating the work done on every one
 * of them.
 */

const MARK = {
	pass: { glyph: '✓', tone: 'var(--ars-good)', bg: 'var(--ars-good-tonal)' },
	warn: { glyph: '!', tone: 'var(--ars-warning)', bg: 'var(--ars-warning-tonal)' },
	fail: { glyph: '✕', tone: 'var(--ars-serious)', bg: 'var(--ars-serious-tonal)' },
	info: { glyph: 'i', tone: 'var(--ars-ink-3)', bg: 'var(--ars-surface-3)' },
};

export default function SiteTests() {
	const [data, setData] = useState(null);
	const [busy, setBusy] = useState(false);
	const [error, setError] = useState(null);

	useEffect(() => {
		api.get('/audit/site-tests').then(setData).catch((e) => setError(e.message));
	}, []);

	const run = async () => {
		setBusy(true);
		setError(null);
		try {
			setData(await api.post('/audit/site-tests'));
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

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

	const tests = data.tests || [];
	const groups = data.groups || {};
	const counts = data.counts || { fail: 0, warn: 0, pass: 0, info: 0 };

	if (!tests.length) {
		return (
			<div className="ars-page">
				{error && <Notice tone="serious">{error}</Notice>}
				<FirstRun
					badge={__('Not run yet', 'ai-rank-suite')}
					ringLabel={__('Site health', 'ai-rank-suite')}
					title={__('The site itself has not been checked yet.', 'ai-rank-suite')}
					why={__('Twenty-one checks on the setup rather than on any page: robots.txt that blocks everything, a default tagline, missing HTTPS, discouraged search engines, no organisation identity, sitemaps that do not resolve. Fast, local, and the faults it finds are the ones no page score can see.', 'ai-rank-suite')}
					action={__('Run the site tests', 'ai-rank-suite')}
					onAction={run}
					busy={busy}
					stats={[{ label: __('Passing', 'ai-rank-suite') }, { label: __('Warnings', 'ai-rank-suite') }, { label: __('Failing', 'ai-rank-suite') }, { label: __('Checks', 'ai-rank-suite') }]}
					previews={[
						{ title: __('Grouped by area', 'ai-rank-suite'), text: __('Indexability, identity, security, structure — each with its checks and the fix in one sentence.', 'ai-rank-suite') },
						{ title: __('Health gauge', 'ai-rank-suite'), text: __('The share of checks passing, weighted so a blocker outweighs a notice.', 'ai-rank-suite') },
						{ title: __('Re-run any time', 'ai-rank-suite'), text: __('Cheap enough to run after every settings change; the audit alerts can mail you when a check flips.', 'ai-rank-suite') },
					]}
				/>
				<Card
					icon={<IconShield size={16} />}
					title={__('Site tests', 'ai-rank-suite')}
					subtitle={__('Twenty-one checks on the site itself, not on its pages', 'ai-rank-suite')}
				>
					<div className="grid gap-3">
						<p className="m-0 text-[13px]" style={{ color: 'var(--ars-ink-2)' }}>
							{__('Some faults belong to no page: a robots.txt that blocks everything, a tagline still reading “Just another WordPress site”, search engine visibility switched off in Settings → Reading. Each one defeats the work done on every page, and none of them shows up in a per-page report.', 'ai-rank-suite')}
						</p>
						<div>
							<Button onClick={run} busy={busy}>
								<IconRefresh size={13} />{__('Run the tests', 'ai-rank-suite')}</Button>
						</div>
					</div>
				</Card>
			</div>
		);
	}

	return (
		<div className="ars-page">
			{error && <Notice tone="serious">{error}</Notice>}

			<ScreenVerdict
				tone={counts.fail > 0 ? 'bad' : counts.warn > 0 ? 'warning' : 'good'}
				text={
					counts.fail > 0
						? sprintf(_n('%1$d of %2$d site checks fails.', '%1$d of %2$d site checks fail.', counts.fail, 'ai-rank-suite'), counts.fail, tests.length)
						: counts.warn > 0
							? sprintf(_n('No site check fails; %d warns.', 'No site check fails; %d warn.', counts.warn, 'ai-rank-suite'), counts.warn)
							: sprintf(__('All %d site checks pass.', 'ai-rank-suite'), tests.length)
				}
				why={
					counts.fail > 0
						? __('A failing site check affects every page at once — fix these before any per-page work.', 'ai-rank-suite')
						: counts.warn > 0
							? __('Warnings are worth a look but block nothing.', 'ai-rank-suite')
							: __('Run again after changing hosting, permalinks or the theme.', 'ai-rank-suite')
				}
			/>
			<Card
				icon={<IconShield size={16} />}
				title={__('Site tests', 'ai-rank-suite')}
				subtitle={__('The setup itself — the faults that belong to no single page', 'ai-rank-suite')}
				action={
					<Button variant="ghost" onClick={run} busy={busy}>
						<IconRefresh size={13} />{__('Run again', 'ai-rank-suite')}</Button>
				}
			>
				{/* The half-circle gauge, not the hero ring — same shape as the
				    dashboard's score, so "how healthy" reads the same everywhere. */}
				<div className="flex gap-5 flex-wrap items-center">
					<Gauge value={data.score} label={__('Site setup', 'ai-rank-suite')} />
					<div className="flex-1 min-w-[300px]">
						<MetricGrid
							columns={4}
							metrics={[
								{
									id: 'fail',
									label: __('Failing', 'ai-rank-suite'),
									hint: __('These cost traffic today rather than eventually.', 'ai-rank-suite'),
									value: counts.fail,
									accent: counts.fail ? 'var(--ars-c-red-ink)' : undefined,
								},
								{
									id: 'warn',
									label: __('Worth fixing', 'ai-rank-suite'),
									hint: __('Not urgent, but each one is a small leak.', 'ai-rank-suite'),
									value: counts.warn,
									accent: counts.warn ? 'var(--ars-accent)' : undefined,
								},
								{
									id: 'pass',
									label: __('Passing', 'ai-rank-suite'),
									value: counts.pass,
									/* The total stays here, on a tile that is always
									   present, so it never disappears with the
									   optional one beside it. */
									sub: sprintf(__('%s tests run', 'ai-rank-suite'), tests.length),
								},
								/*
								 * The fourth status, which the row used to drop.
								 * Response time, pages on noindex and unpublished
								 * drafts are readings, not verdicts — there is
								 * nothing to fix — but leaving them out of the
								 * breakdown made the three numbers disagree with
								 * the total beside them.
								 */
								( counts.info ?? 0 ) > 0 && {
									id: 'info',
									label: __('Noted', 'ai-rank-suite'),
									hint: __('Readings rather than verdicts: nothing to fix, but worth knowing. They do not affect the score.', 'ai-rank-suite'),
									value: counts.info,
									sub: __('not scored', 'ai-rank-suite'),
								},
							].filter(Boolean)}
						/>
					</div>
				</div>
				{data.ran_at > 0 && (
					<p className="m-0 mt-3 t-caption">{sprintf(__('Last run %s.', 'ai-rank-suite'), new Date(data.ran_at * 1000).toLocaleString())}</p>
				)}
			</Card>

			{Object.entries(groups).map(([id, label]) => {
				const rows = tests.filter((t) => t.group === id);
				if (!rows.length) return null;
				const open = rows.filter((t) => t.status === 'fail' || t.status === 'warn');
				return (
					<Card
						key={id}
						title={label}
						action={
							open.length === 0 ? (
								<Badge tone="good">✓ {__('All good', 'ai-rank-suite')}</Badge>
							) : (
								<Badge tone={rows.some((t) => t.status === 'fail') ? 'serious' : 'warning'}>
									{sprintf(_n('%d to fix', '%d to fix', open.length, 'ai-rank-suite'), open.length)}
								</Badge>
							)
						}
						flush
					>
						<div className="ars-table-wrap">
							<table className="ars-table">
								<thead>
									<tr>
										<th style={{ width: 34 }} />
										<th style={{ width: 260 }}>{__('Test', 'ai-rank-suite')}</th>
										<th style={{ width: 260 }}>{__('What it found', 'ai-rank-suite')}</th>
										<th>{__('Why it matters', 'ai-rank-suite')}</th>
									</tr>
								</thead>
								<tbody>
									{rows.map((t) => {
										const mark = MARK[t.status] || MARK.info;
										return (
											<tr key={t.id}>
												<td style={{ width: 34 }}>
													<span
														aria-hidden
														className="inline-flex items-center justify-center"
														style={{
															width: 17,
															height: 17,
															borderRadius: 'var(--ars-r-xs)',
															background: mark.bg,
															color: mark.tone,
															fontSize: 11,
															fontWeight: 700,
														}}
													>
														{mark.glyph}
													</span>
												</td>
												<td style={{ fontWeight: t.status === 'pass' ? 400 : 600 }}>{t.label}</td>
												<td style={{ color: 'var(--ars-ink-2)' }}>{t.value}</td>
												<td style={{ color: 'var(--ars-ink-2)' }}>{t.fix}</td>
											</tr>
										);
									})}
								</tbody>
							</table>
						</div>
					</Card>
				);
			})}
		</div>
	);
}
