import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Badge, Notice, ChipBar } from './ui';
import Explain from './Explain';
import { IconRefresh, IconGoogle, IconExternal } from './icons';

/**
 * Google rich result eligibility, per type.
 *
 * The screen exists because "is my job posting valid" is a question with a
 * definite answer that nobody can get without pasting URLs into Google's
 * testing tool one at a time. The graph is right here; Google publishes the
 * required properties; the check is arithmetic.
 *
 * Required and recommended are kept visually apart. A missing required
 * property means the page is not eligible at all. A missing recommended one
 * means the result renders with less in it. Treating both as errors produces a
 * screen full of red that nobody can prioritise, which is the failure mode of
 * every structured-data tool.
 */
export default function RichResults() {
	const [data, setData] = useState(null);
	const [error, setError] = useState(null);
	const [busy, setBusy] = useState(false);
	const [filter, setFilter] = useState('present');
	const [open, setOpen] = useState(null);

	const load = (fresh = false) => {
		setBusy(true);
		api
			.get(`/google/rich-results${fresh ? '?fresh=1' : ''}`)
			.then(setData)
			.catch((e) => setError(e.message))
			.finally(() => setBusy(false));
	};

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

	if (error) return <Notice tone="serious">{error}</Notice>;
	if (!data) return <Card>{__('Reading the structured data on your pages…', 'ai-rank-suite')}</Card>;

	const features = data.features || [];
	const present = features.filter((f) => f.pages > 0);
	const broken = present.filter((f) => f.invalid > 0);
	const opportunities = features.filter((f) => f.pages === 0 && !f.retired);

	const shown =
		filter === 'present' ? present : filter === 'broken' ? broken : filter === 'gaps' ? opportunities : features;

	return (
		<div className="grid gap-3">
			<div className="grid gap-3 sm:grid-cols-3">
				<div className="ars-rr-stat">
					<b>{present.length}</b>
					<span>{__('rich result types on this site', 'ai-rank-suite')}</span>
				</div>
				<div className={`ars-rr-stat${broken.length ? ' is-bad' : ''}`}>
					<b>{broken.length}</b>
					<span>{__('with pages that would not qualify', 'ai-rank-suite')}</span>
				</div>
				<div className="ars-rr-stat">
					<b>{data.scanned}</b>
					<span>{__('pages inspected', 'ai-rank-suite')}</span>
				</div>
			</div>

			<Card
				icon={<IconGoogle size={16} />}
				title={__('Rich result eligibility', 'ai-rank-suite')}
				subtitle={__('Checked against the properties Google documents as required for each feature — not a guess, the graph is read from your pages', 'ai-rank-suite')}
				action={
					<div className="flex items-center gap-2">
						<Button variant="ghost" busy={busy} onClick={() => load(true)}>
							<IconRefresh size={13} />{__('Rescan', 'ai-rank-suite')}</Button>
					</div>
				}
				flush
			>
				<div className="p-3" style={{ borderBottom: '1px solid var(--ars-border)' }}>
					<ChipBar
						label={__('Show', 'ai-rank-suite')}
						value={filter}
						onChange={setFilter}
						options={[
							{ id: 'present', label: __('On this site', 'ai-rank-suite'), count: present.length },
							{ id: 'broken', label: __('Not qualifying', 'ai-rank-suite'), count: broken.length },
							{ id: 'gaps', label: __('Not used yet', 'ai-rank-suite'), count: opportunities.length },
							{ id: 'all', label: __('Everything', 'ai-rank-suite'), count: features.length },
						]}
					/>
				</div>

				{shown.length === 0 ? (
					<p className="m-0 p-4 text-[13px]" style={{ color: 'var(--ars-ink-2)' }}>
						{filter === 'broken'
							? __('Every page that emits a rich result type meets its required properties.', 'ai-rank-suite')
							: __('Nothing in this group.', 'ai-rank-suite')}
					</p>
				) : (
					<div>
						{shown.map((f) => {
							const isOpen = open === f.type;
							const state = f.pages === 0 ? 'none' : f.invalid === 0 ? 'good' : 'bad';
							return (
								<div key={f.type} className={`ars-rr-row is-${state}`}>
									<button
										type="button"
										className="ars-rr-main"
										onClick={() => setOpen(isOpen ? null : f.type)}
										aria-expanded={isOpen}
									>
										<span className="ars-rr-caret" aria-hidden>
											{isOpen ? '▾' : '▸'}
										</span>
										<span className="min-w-0">
											<span className="flex items-center gap-2 flex-wrap">
												<b className="text-[13px]">{f.label}</b>
												<span className="ars-tag">{f.group}</span>
												{f.indexing && (
													<span
														className="ars-tag"
														style={{ background: 'var(--ars-brand-tonal)', color: 'var(--ars-brand-tonal-ink)' }}
														title={__('One of only two types the Google Indexing API accepts', 'ai-rank-suite')}
													>{__('Indexing API', 'ai-rank-suite')}</span>
												)}
												{f.retired && <span className="ars-tag">{__('retired by Google', 'ai-rank-suite')}</span>}
											</span>
											<span className="ars-rr-about">{f.about}</span>
										</span>
										<span className="ars-rr-count">
											{f.pages === 0 ? (
												<i style={{ color: 'var(--ars-ink-3)' }}>{__('not used', 'ai-rank-suite')}</i>
											) : (
												<>
													<b className="tabular-nums">{f.valid}</b> {__('of', 'ai-rank-suite')}{' '}
													<span className="tabular-nums">{f.pages}</span> {__('qualify', 'ai-rank-suite')}
												</>
											)}
										</span>
										{f.pages > 0 &&
											(f.invalid === 0 ? (
												<Badge tone="good">{__('valid', 'ai-rank-suite')}</Badge>
											) : (
												<Badge tone="serious">{sprintf(__('%d failing', 'ai-rank-suite'), f.invalid)}</Badge>
											))}
									</button>

									{isOpen && (
										<div className="ars-rr-body">
											{f.gaps.length > 0 && (
												<div>
													<div className="t-overline">{__('Missing required properties', 'ai-rank-suite')}</div>
													<p className="m-0 mb-2 t-caption">{__('A page without these is not eligible for this rich result at all.', 'ai-rank-suite')}</p>
													<div className="ars-rr-props">
														{f.gaps.map((g) => (
															<div key={g.property} className="ars-rr-prop is-required">
																<code>{g.property}</code>
																<span>
																	missing on {g.pages} page{g.pages === 1 ? '' : 's'}
																</span>
																{f.notes?.[g.property] && <em>{f.notes[g.property]}</em>}
															</div>
														))}
													</div>
												</div>
											)}

											{f.weak.length > 0 && (
												<div>
													<div className="t-overline">{__('Recommended but absent', 'ai-rank-suite')}</div>
													<p className="m-0 mb-2 t-caption">{__('The page still qualifies. The result just renders with less in it.', 'ai-rank-suite')}</p>
													<div className="ars-rr-props">
														{f.weak.map((g) => (
															<div key={g.property} className="ars-rr-prop">
																<code>{g.property}</code>
																<span>
																	on {g.pages} page{g.pages === 1 ? '' : 's'}
																</span>
																{f.notes?.[g.property] && <em>{f.notes[g.property]}</em>}
															</div>
														))}
													</div>
												</div>
											)}

											{f.samples.length > 0 && (
												<div>
													<div className="t-overline">{__('Pages that would not qualify', 'ai-rank-suite')}</div>
													<ul className="m-0 mt-1.5 p-0 list-none grid gap-1">
														{f.samples.map((s) => (
															<li key={s.id} className="ars-rr-sample">
																<button
																	type="button"
																	className="ars-linkbtn"
																	onClick={() => {
																		window.location.hash = `/content/${s.id}`;
																	}}
																>
																	{s.title || `#${s.id}`}
																</button>
																<span className="t-caption">{sprintf(__('missing %s', 'ai-rank-suite'), s.missing.join(', '))}</span>
															</li>
														))}
													</ul>
												</div>
											)}

											{f.pages === 0 && (
												<div className="grid gap-2">
													<p className="m-0 text-[12.5px]">
														{sprintf(__('No page on this site emits %s. Required to qualify:', 'ai-rank-suite'), f.type)}{' '}
														{f.required.map((p) => (
															<code key={p} className="ars-head-code mr-1">
																{p}
															</code>
														))}
													</p>
													<button
														type="button"
														className="ars-linkbtn text-left"
														onClick={() => {
															window.location.hash = '/schema';
														}}
													>
														{sprintf(__('Add %s markup in Schema →', 'ai-rank-suite'), f.label)}
													</button>
												</div>
											)}

											{f.pages > 0 && f.invalid === 0 && f.weak.length === 0 && (
												<p className="m-0 text-[12.5px]">
													{sprintf(__('Every page emitting %s has all required and all recommended properties.', 'ai-rank-suite'), f.type)}
												</p>
											)}

											<a
												href={`https://search.google.com/test/rich-results`}
												target="_blank"
												rel="noreferrer"
												className="inline-flex items-center gap-1 text-[12px]"
											>{__('Verify one page in Google\'s own tester', 'ai-rank-suite')}<IconExternal size={10} />
											</a>
										</div>
									)}
								</div>
							);
						})}
					</div>
				)}
			</Card>

			<Explain title={__('The Indexing API is not what most plugins claim it is', 'ai-rank-suite')}>
				<p>{__('Google documents the Indexing API as supporting exactly two types:', 'ai-rank-suite')}<code>{__('JobPosting', 'ai-rank-suite')}</code> {__('and', 'ai-rank-suite')}{' '}
					<code>{__('BroadcastEvent', 'ai-rank-suite')}</code>. {__('Submitting a blog post or a product page to it does not get that page indexed faster — it uses quota and returns success, which is why the misunderstanding is so durable. Plugins that advertise it as “instant indexing for everything” are selling that misunderstanding.', 'ai-rank-suite')}
				</p>
				<p>
					{__('For everything else the honest tools are the sitemap, IndexNow — which Bing, Yandex, Seznam and Naver genuinely act on — and publishing something worth crawling. All three are in this plugin, on the tabs beside this one.', 'ai-rank-suite')}
				</p>
				<p>
					{sprintf(__('This scan reads the last %d modified pages rather than every page on the site. That is enough to find a broken template, which is what a site-wide structured data problem always is; it is not a complete audit, and it says so rather than implying it counted everything.', 'ai-rank-suite'), data.limit)}
				</p>
			</Explain>
		</div>
	);
}
