import React, { useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { useSettings } from '../useSettings';
import { api } from '../api';
import { Card, Button, Badge, Notice, Switch, MetricGrid, SectionTitle, PageState } from '../components/ui';

const SELECTS = [
	{ key: 'condition', label: __('Default condition', 'ai-rank-suite') },
	{ key: 'age_group', label: __('Age group', 'ai-rank-suite') },
	{ key: 'gender', label: __('Gender', 'ai-rank-suite') },
	{ key: 'adult', label: __('Adult content', 'ai-rank-suite') },
	{ key: 'size_system', label: __('Size system', 'ai-rank-suite') },
	{ key: 'size_type', label: __('Size type', 'ai-rank-suite') },
];

export default function Feeds() {
	const { data, setData, s, update, save, busy, saved, error, setError } = useSettings('/settings/feeds');
	// Rebuilding has its own flag: it must not disable Save, and Save must not
	// make the rebuild button look busy.
	const [rebuilding, setRebuilding] = useState(false);

	if (!data) return <PageState error={error} />;
	const options = data.options || {};

	const rebuild = async () => {
		setRebuilding(true);
		setError(null);
		try {
			setData(await api.post('/feeds/rebuild', {}));
		} catch (e) {
			setError(e.message);
		} finally {
			setRebuilding(false);
		}
	};

	const TARGETS = [
		{
			key: 'google',
			flag: 'google_enabled',
			label: __('Google Merchant Center', 'ai-rank-suite'),
			hint: __('Shopping ads, free listings and the Shopping tab', 'ai-rank-suite'),
		},
		{
			key: 'meta',
			flag: 'meta_enabled',
			label: __('Meta Commerce Manager', 'ai-rank-suite'),
			hint: __('Facebook and Instagram Shops, catalog ads', 'ai-rank-suite'),
		},
	];

	return (
		<div className="ars-page">
			{error && <Notice tone="serious">{error}</Notice>}
			{!data.woo_active && (
				<Notice tone="info">{__('Catalog feeds need WooCommerce — activate it and this page fills itself in.', 'ai-rank-suite')}</Notice>
			)}
			{!data.permalinks && (
				<Notice tone="serious">{__('Feeds need pretty permalinks. Switch Settings → Permalinks away from “Plain” first.', 'ai-rank-suite')}</Notice>
			)}

			{/* The hero that used to sit here said "one catalog, two platforms" at
			    24px; the masthead already names the screen, so the pitch survives
			    as the section's hint and nothing else does. */}
			<section className="grid gap-2">
				<SectionTitle hint={__('One catalog, two platforms — paste the URL and your products appear. No export, no spreadsheet, no sync plugin.', 'ai-rank-suite')}>{__('Feed targets', 'ai-rank-suite')}</SectionTitle>
				<div className="grid gap-4 sm:grid-cols-2">
					{TARGETS.map((t) => {
						const stat = data.feeds[t.key] || {};
						const on = !!s[t.flag];
						return (
							<Card key={t.key} title={t.label} subtitle={t.hint}>
								<div className="grid gap-3">
									<Switch checked={on} onChange={(v) => update({ [t.flag]: v })} label={__('Publish this feed', 'ai-rank-suite')} />
									{on && (
										<>
											<div
												className="ars-r-lg px-4 py-3 grid gap-1.5"
												style={{ background: 'var(--ars-surface-2)' }}
											>
												<a
													href={stat.url}
													target="_blank"
													rel="noreferrer"
													className="ars-mono text-[12px] ars-url"
													title={stat.url}
												>
													{stat.url}
												</a>
												<div className="flex items-center gap-2">
													{stat.cached ? (
														<Badge tone="good">
															✓ {sprintf(__('%1$s items · %2$s KB', 'ai-rank-suite'), stat.items, Math.round(stat.bytes / 1024))}
														</Badge>
													) : (
														<Badge tone="neutral">{__('Not built yet', 'ai-rank-suite')}</Badge>
													)}
												</div>
											</div>
											<p className="m-0 text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Paste this URL as a scheduled fetch. The feed rebuilds itself whenever a product changes.', 'ai-rank-suite')}</p>
										</>
									)}
								</div>
							</Card>
						);
					})}
				</div>
			</section>

			<Card
				title={__('Catalog defaults', 'ai-rank-suite')}
				subtitle={__('Applied to every product that has no value of its own — individual products always win', 'ai-rank-suite')}
				action={
					<div className="flex items-center gap-2">
						{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
						<Button variant="ghost" onClick={rebuild} busy={rebuilding}>{__('Rebuild now', 'ai-rank-suite')}</Button>
						<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
					</div>
				}
			>
				<div className="grid gap-4">
					<div className="grid gap-3 sm:grid-cols-3">
						{SELECTS.map((f) => (
							<div key={f.key}>
								<label className="block font-medium mb-1 text-[12.5px]">{f.label}</label>
								<select value={s[f.key] ?? ''} onChange={(e) => update({ [f.key]: e.target.value })}>
									{(options[f.key] || ['']).map((v) => (
										<option key={v} value={v}>
											{v === '' ? __('— not set —', 'ai-rank-suite') : v}
										</option>
									))}
								</select>
							</div>
						))}
					</div>

					<div>
						<label className="block font-medium mb-1 text-[12.5px]">{__('Google product category ID', 'ai-rank-suite')}</label>
						<input
							type="text"
							placeholder={__('e.g. 187 (Apparel & Accessories &gt; Shoes)', 'ai-rank-suite')}
							value={s.google_category}
							onChange={(e) => update({ google_category: e.target.value })}
						/>
						<div className="text-[11.5px] mt-1" style={{ color: 'var(--ars-ink-3)' }}>
							{__('The numeric id from', 'ai-rank-suite')}{' '}
							<a href="https://www.google.com/basepages/producttype/taxonomy-with-ids.en-US.txt" target="_blank" rel="noreferrer">{__('Google’s product taxonomy', 'ai-rank-suite')}</a>
							. {__('Products can override it individually.', 'ai-rank-suite')}
						</div>
					</div>

					<div className="grid gap-3 sm:grid-cols-3">
						<div>
							<label className="block font-medium mb-1 text-[12.5px]">{__('Max items', 'ai-rank-suite')}</label>
							<input
								type="number"
								min="1"
								max="10000"
								value={s.max_items}
								onChange={(e) => update({ max_items: Number(e.target.value) || 1 })}
							/>
						</div>
						<div>
							<label className="block font-medium mb-1 text-[12.5px]">{__('Cache (hours)', 'ai-rank-suite')}</label>
							<input
								type="number"
								min="1"
								max="168"
								value={s.cache_hours}
								onChange={(e) => update({ cache_hours: Number(e.target.value) || 1 })}
							/>
						</div>
					</div>

					<Switch
						checked={!!s.variations}
						onChange={(v) => update({ variations: v })}
						label={__('List variations as individual items (recommended for apparel)', 'ai-rank-suite')}
					/>
					<Switch
						checked={!!s.exclude_out_of_stock}
						onChange={(v) => update({ exclude_out_of_stock: v })}
						label={__('Leave out-of-stock products out of the feed', 'ai-rank-suite')}
					/>
				</div>
			</Card>

			{/* An unbuilt feed has no item count — an em-dash says "not measured"
			    where a zero would claim an empty catalog. */}
			{/* Zero items is never left unexplained: the backend walks the same
			    funnel the feed builder does and names the step that emptied it. */}
			{data.woo_active && data.empty_why && (
				<Notice tone={data.empty_why.reason === 'not_built' ? 'info' : 'warning'}>
					<strong>{__('Feed is empty:', 'ai-rank-suite')}</strong> {data.empty_why.message} {data.empty_why.action}
					{data.empty_why.counts && Object.keys(data.empty_why.counts).length > 0 && (
						<span className="t-caption block mt-1">
							{Object.entries(data.empty_why.counts)
								.map(([k, v]) => `${k.replace(/_/g, ' ')}: ${v}`)
								.join(' · ')}
						</span>
					)}
				</Notice>
			)}

			{data.woo_active && (
				<MetricGrid
					columns={3}
					metrics={[
						{
							id: 'google-items',
							label: __('Google items', 'ai-rank-suite'),
							hint: __('Products in the built Google Merchant feed.', 'ai-rank-suite'),
							value: data.feeds.google?.items ?? '—',
							sub: data.feeds.google?.items ? __('in the built feed', 'ai-rank-suite') : data.empty_why ? data.empty_why.message : __('not built yet', 'ai-rank-suite'),
						},
						{
							id: 'meta-items',
							label: __('Meta items', 'ai-rank-suite'),
							hint: __('Products in the built Meta catalog feed.', 'ai-rank-suite'),
							value: data.feeds.meta?.items ?? '—',
							sub: data.feeds.meta?.items ? __('in the built feed', 'ai-rank-suite') : data.empty_why ? data.empty_why.message : __('not built yet', 'ai-rank-suite'),
						},
						{
							id: 'feed-size',
							label: __('Feed size', 'ai-rank-suite'),
							hint: __('The cached Google feed on disk. Built once, then served instantly.', 'ai-rank-suite'),
							value: data.feeds.google?.bytes == null ? '—' : Math.round(data.feeds.google.bytes / 1024),
							unit: data.feeds.google?.bytes == null ? '' : 'KB',
							sub: data.feeds.google?.bytes == null ? __('not built yet', 'ai-rank-suite') : __('cached, served instantly', 'ai-rank-suite'),
						},
					]}
				/>
			)}
		</div>
	);
}
