import React, { useEffect, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Notice, MetricGrid, ScoreRing, Badge, SectionTitle } from '../components/ui';
import StoreAudit from '../components/StoreAudit';

/**
 * The shop, on one screen.
 *
 * A merchant does not think in "feeds", "schema" and "content"; they think
 * in products that sell and products that do not. This screen starts with
 * one number, how ready the catalogue is for search and for AI answers, then
 * the four things that number is made of, then the ten products that pull it
 * down, and only then the machinery: feeds, schema, the full catalogue audit.
 */
export default function Shop() {
	const [data, setData] = useState(null);
	const [error, setError] = useState(null);
	const [busy, setBusy] = useState(false);

	const load = (fresh = false) => {
		setBusy(true);
		api
			.get(`/store/overview${fresh ? '?fresh=1' : ''}`)
			.then(setData)
			.catch((e) => setError(e.message))
			.finally(() => setBusy(false));
	};
	useEffect(() => {
		load();
	}, []);

	const go = (hash) => {
		window.location.hash = hash;
	};

	if (error) return <Notice tone="serious">{error}</Notice>;
	if (!data) return <Card>{__('Reading the shop…', 'ai-rank-suite')}</Card>;
	if (!data.active) return <Notice tone="warning">{__('WooCommerce is not active on this site.', 'ai-rank-suite')}</Notice>;

	const c = data.counts || {};
	const tone = (v) => (v >= 80 ? 'good' : v >= 50 ? 'warn' : 'bad');
	const verdict =
		data.readiness >= 80
			? __('Your catalogue is ready for search and for AI answers.', 'ai-rank-suite')
			: data.readiness >= 50
				? __('Your catalogue is findable, but a part of it is invisible where it matters.', 'ai-rank-suite')
				: __('Most of your catalogue cannot be shown as products by Google or quoted by an AI yet.', 'ai-rank-suite');

	const gaps = [
		{ id: 'no_image', label: __('Without image', 'ai-rank-suite'), value: c.no_image ?? 0 },
		{ id: 'no_price', label: __('Without price', 'ai-rank-suite'), value: c.no_price ?? 0 },
		{ id: 'no_gtin', label: __('Without GTIN', 'ai-rank-suite'), value: c.no_gtin ?? 0 },
		{ id: 'thin', label: __('Thin description', 'ai-rank-suite'), value: c.thin ?? 0, hint: __('Under 200 characters. An AI answer has nothing to quote.', 'ai-rank-suite') },
		{ id: 'no_meta_desc', label: __('No meta description', 'ai-rank-suite'), value: c.no_meta_desc ?? 0 },
		{ id: 'stranded', label: __('Out of stock, still indexed', 'ai-rank-suite'), value: c.stranded ?? 0 },
	];

	return (
		<div className="grid gap-4">
			<Card>
				<div className="ars-hero">
					<div className="ars-hero-ring">
						<ScoreRing value={data.readiness} label={__('Shop readiness', 'ai-rank-suite')} />
						<p className="t-caption ars-hero-ring-note">
							{sprintf(
								/* translators: %s: number of products. */
								_n('%s published product', '%s published products', data.products, 'ai-rank-suite'),
								data.products.toLocaleString()
							)}
						</p>
					</div>
					<div className="ars-hero-body">
						<span className={`ars-hero-badge is-${tone(data.readiness) === 'good' ? 'good' : tone(data.readiness) === 'warn' ? 'warning' : 'bad'}`}>
							{__('Shop readiness', 'ai-rank-suite')}
						</span>
						<h2 className="ars-hero-title">{verdict}</h2>
						<p className="ars-hero-why">
							{__('Four things make the number: product data, product text, sellable pages and product schema. Each one below says what it is missing.', 'ai-rank-suite')}
						</p>
						<div className="ars-hero-actions">
							<Button onClick={() => go('/content')}>{__('Optimise products', 'ai-rank-suite')}</Button>
							<Button variant="ghost" onClick={() => load(true)} busy={busy}>
								{__('Re-read the catalogue', 'ai-rank-suite')}
							</Button>
						</div>
					</div>
				</div>
				<div className="ars-hero-stats">
					{(data.pillars || []).map((p) => (
						<div key={p.id} className="ars-hero-stat" title={p.hint}>
							<span className={`ars-hero-stat-v is-${tone(p.score)}`}>{p.score} / 100</span>
							<span className="ars-hero-stat-l">{p.label}</span>
							<span className="ars-hero-stat-h">{p.hint}</span>
						</div>
					))}
				</div>
			</Card>

			<Card
				title={__('Where the catalogue is short', 'ai-rank-suite')}
				subtitle={__('Products, not percentages. Each tile is a list of products to fix.', 'ai-rank-suite')}
			>
				<MetricGrid
					columns={3}
					metrics={gaps.map((g) => ({
						id: g.id,
						label: g.label,
						value: Number(g.value).toLocaleString(),
						sub: g.hint || (data.products ? sprintf(__('%d%% of the catalogue', 'ai-rank-suite'), Math.round((g.value / data.products) * 100)) : ''),
						accent: g.value === 0 ? 'var(--ars-good)' : 'var(--ars-warning)',
					}))}
				/>
			</Card>

			<div className="grid gap-4 lg:grid-cols-2">
				<Card
					title={__('Products pulling the score down', 'ai-rank-suite')}
					subtitle={
						data.unscored > 0
							? sprintf(
									/* translators: %s: number of products without a score. */
									_n('%s product has no score yet; analyse it under Content.', '%s products have no score yet; analyse them under Content.', data.unscored, 'ai-rank-suite'),
									data.unscored.toLocaleString()
							  )
							: __('The ten lowest AI-search scores in the catalogue.', 'ai-rank-suite')
					}
					action={<Button variant="ghost" onClick={() => go('/content')}>{__('All products', 'ai-rank-suite')}</Button>}
				>
					{(data.weakest || []).length === 0 ? (
						<p className="t-caption">{__('No product has been scored yet. Open Content and analyse the catalogue once; the queue appears here.', 'ai-rank-suite')}</p>
					) : (
						<ul className="ars-board">
							{data.weakest.map((p) => (
								<li key={p.id} className="ars-board-row is-clickable">
									<button type="button" className="ars-board-hit" onClick={() => go(`/content/${p.id}`)}>
										<span className="ars-board-label" title={p.title}>{p.title}</span>
										<span className="ars-board-value tabular-nums">
											<Badge tone={tone(p.score) === 'good' ? 'good' : tone(p.score) === 'warn' ? 'warning' : 'serious'}>{p.score} / 100</Badge>
										</span>
									</button>
								</li>
							))}
						</ul>
					)}
				</Card>

				<div className="grid gap-4">
					<Card
						title={__('Product schema', 'ai-rank-suite')}
						subtitle={__('What a product page tells Google and the AI engines as structured data.', 'ai-rank-suite')}
						action={<Button variant="ghost" onClick={() => go('/schema/products')}>{__('Settings', 'ai-rank-suite')}</Button>}
					>
						<div className="grid gap-2">
							{[
								['product_schema', __('Product with price and availability', 'ai-rank-suite')],
								['identifiers', __('GTIN, MPN and brand', 'ai-rank-suite')],
								['shipping_details', __('Shipping details', 'ai-rank-suite')],
								['return_policy', __('Return policy', 'ai-rank-suite')],
								['noindex_cart', __('Cart and checkout kept out of the index', 'ai-rank-suite')],
							].map(([key, label]) => (
								<div key={key} className="flex items-center justify-between gap-3 text-[13px]">
									<span>{label}</span>
									<Badge tone={data.schema?.[key] ? 'good' : 'warning'}>{data.schema?.[key] ? __('On', 'ai-rank-suite') : __('Off', 'ai-rank-suite')}</Badge>
								</div>
							))}
						</div>
					</Card>

					<Card
						title={__('Catalog feeds', 'ai-rank-suite')}
						subtitle={__('The files Google Merchant Center and Meta read the catalogue from.', 'ai-rank-suite')}
						action={<Button variant="ghost" onClick={() => go('/feeds')}>{__('Feeds', 'ai-rank-suite')}</Button>}
					>
						<div className="grid gap-2 text-[13px]">
							{[
								['google', __('Google Merchant', 'ai-rank-suite')],
								['meta', __('Meta catalogue', 'ai-rank-suite')],
							].map(([key, label]) => {
								const f = data.feeds?.[key] || {};
								return (
									<div key={key} className="flex items-center justify-between gap-3">
										<span>{label}</span>
										{f.items === null || f.items === undefined ? (
											<Badge tone="neutral">{__('Not built', 'ai-rank-suite')}</Badge>
										) : (
											<Badge tone="good">{sprintf(_n('%s item', '%s items', f.items, 'ai-rank-suite'), Number(f.items).toLocaleString())}</Badge>
										)}
									</div>
								);
							})}
						</div>
					</Card>
				</div>
			</div>

			<SectionTitle hint={__('Index bloat, dead ends, category text and the data gaps, counted across the whole catalogue.', 'ai-rank-suite')}>
				{__('Catalogue audit', 'ai-rank-suite')}
			</SectionTitle>
			<StoreAudit />
		</div>
	);
}
