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

export default function Packs() {
	const [data, setData] = useState(null);
	const [pack, setPack] = useState('');
	const [region, setRegion] = useState('');
	const [city, setCity] = useState('');
	const [busy, setBusy] = useState(false);
	const [result, setResult] = useState(null);
	const [error, setError] = useState(null);

	useEffect(() => {
		api
			.get('/packs')
			.then((d) => {
				setData(d);
				if (d.applied) {
					setPack(d.applied.pack);
					setRegion(d.applied.region);
					setCity(d.applied.city || '');
				}
			})
			.catch((e) => setError(e.message));
	}, []);

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

	const chosen = data.packs.find((p) => p.id === pack);
	const chosenRegion = data.regions.find((r) => r.id === region);

	const apply = async () => {
		setBusy(true);
		setError(null);
		try {
			setResult(await api.post('/packs/apply', { pack, region, city }));
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	return (
		<div className="ars-page">
			<Card
				title={__('Industry packs', 'ai-rank-suite')}
				subtitle={__('Your trade and your market, turned into a configured site', 'ai-rank-suite')}
				action={
					data.applied ? (
						<Badge tone="good">
							✓ {data.packs.find((p) => p.id === data.applied.pack)?.label} ·{' '}
							{data.regions.find((r) => r.id === data.applied.region)?.short}
						</Badge>
					) : (
						<Badge tone="neutral">{__('Nothing applied yet', 'ai-rank-suite')}</Badge>
					)
				}
			>
				<Explain title={__('What a pack actually does — and what it never does', 'ai-rank-suite')}>
					<p>{__('A dentist does not know that schema.org has a Dentist type, that', 'ai-rank-suite')}{' '}<code>knowsAbout</code>{' '}
						{__('is the strongest expertise signal an assistant reads, or which four questions patients type into ChatGPT before booking. They know they run a practice in Munich. A pack turns that one fact into configuration.', 'ai-rank-suite')}
					</p>
					<p>
						{__('Applying a pack is additive. It fills empty fields, adds subjects and prompts that are not already there, and leaves every value you have typed exactly as it is — so pressing it twice is safe, and pressing it after months of tuning does not undo any of that tuning.', 'ai-rank-suite')}
					</p>
				</Explain>
			</Card>

			<Card title={__('1 · What do you do?', 'ai-rank-suite')} subtitle={__('Sets the schema type, the subjects you claim, and the questions worth watching', 'ai-rank-suite')}>
				<div className="ars-cardgrid" style={{ ["--min"]: "250px" }}>
					{data.packs.map((p) => (
						<button
							key={p.id}
							type="button"
							onClick={() => setPack(p.id)}
							className={`ars-pick${pack === p.id ? ' is-active' : ''}`}
						>
							{/* The emoji the API ships (⚖️, 🍽️, 🏘️ — VS16 sequences) do not
							    resolve in every admin environment: some cards showed a
							    tofu box, some a half-drawn glyph, some nothing at all but
							    kept the indent, so no two titles started at the same x.
							    The label carries the meaning on its own. */}
							<span className="ars-pick-title">
								{p.label}
								{pack === p.id && <span style={{ marginLeft: 'auto', color: 'var(--ars-brand)' }}>✓</span>}
							</span>
							<span className="ars-pick-note">{p.summary}</span>
						</button>
					))}
				</div>
			</Card>

			<Card title={__('2 · Which market?', 'ai-rank-suite')} subtitle={__('Currency, payment methods, languages and the identifiers that market asks for', 'ai-rank-suite')}>
				<div className="ars-cardgrid" style={{ ["--min"]: "250px" }}>
					{data.regions.map((r) => (
						<button
							key={r.id}
							type="button"
							onClick={() => setRegion(r.id)}
							className={`ars-pick${region === r.id ? ' is-active' : ''}`}
						>
							<span className="ars-pick-title">
								{r.label}
								{region === r.id && <span style={{ marginLeft: 'auto', color: 'var(--ars-brand)' }}>✓</span>}
							</span>
							<span className="ars-pick-note">
								{r.currency} · {r.languages.join(', ')}
								{r.countries.length > 0 ? ` · ${r.countries.join(', ')}` : ''}
							</span>
						</button>
					))}
				</div>
			</Card>

			{chosen && chosenRegion && (
				<Card title={__('3 · Where are you based?', 'ai-rank-suite')} subtitle={__('Used to write the local prompts — leave blank if you sell online only', 'ai-rank-suite')}>
					<div className="grid gap-3">
						<div className="max-w-[320px]">
							<label className="block font-medium mb-1">{__('City', 'ai-rank-suite')}</label>
							<input type="text" value={city} placeholder={__('Dubai', 'ai-rank-suite')} onChange={(e) => setCity(e.target.value)} />
						</div>

						<div
							className="p-3 grid gap-2"
							style={{ background: 'var(--ars-surface-2)', borderRadius: 'var(--ars-r-sm)' }}
						>
							<div className="t-overline">{__('Why this pack matters', 'ai-rank-suite')}</div>
							<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
								{chosen.why}
							</p>
							<div className="flex flex-wrap gap-1 mt-1">
								{chosen.schema.map((t) => (
									<span
										key={t}
										className="ars-tag"
										style={{ background: 'var(--ars-c-blue)', color: 'var(--ars-c-blue-ink)' }}
									>
										{t}
									</span>
								))}
							</div>
						</div>

						<div className="flex items-center gap-2 flex-wrap">
							<Button onClick={apply} busy={busy} disabled={!pack || !region}>{__('Apply pack', 'ai-rank-suite')}</Button>
							<span className="text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Nothing you have already set will be overwritten.', 'ai-rank-suite')}</span>
						</div>
						{error && <Notice tone="serious">{error}</Notice>}
					</div>
				</Card>
			)}

			{result && (
				<>
					<Card title={__('What changed', 'ai-rank-suite')} subtitle={__('And what was deliberately left alone', 'ai-rank-suite')}>
						<div className="grid gap-3 md:grid-cols-2">
							<div>
								<div className="t-overline mb-1.5">{__('Applied', 'ai-rank-suite')}</div>
								{result.changed.length === 0 ? (
									<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Everything this pack sets was already in place.', 'ai-rank-suite')}</p>
								) : (
									<ul className="m-0 pl-5 grid gap-1 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
										{result.changed.map((c, i) => (
											<li key={i}>{c}</li>
										))}
									</ul>
								)}
							</div>
							<div>
								<div className="t-overline mb-1.5">{__('Left as you set it', 'ai-rank-suite')}</div>
								{result.kept.length === 0 ? (
									<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Nothing to preserve — these fields were empty.', 'ai-rank-suite')}</p>
								) : (
									<ul className="m-0 pl-5 grid gap-1 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>
										{result.kept.map((c, i) => (
											<li key={i}>{c}</li>
										))}
									</ul>
								)}
							</div>
						</div>
					</Card>

					<Card title={__('Do these next', 'ai-rank-suite')} subtitle={__('What the pack cannot fill in for you', 'ai-rank-suite')}>
						<div className="grid gap-4">
							<div>
								<div className="t-overline mb-1.5">{__('Market notes', 'ai-rank-suite')}</div>
								<ul className="m-0 pl-5 grid gap-1.5 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
									{result.notes.map((n, i) => (
										<li key={i}>{n}</li>
									))}
								</ul>
							</div>
							<div className="grid gap-4 md:grid-cols-2">
								<div>
									<div className="t-overline mb-1.5">{__('Identifiers worth adding', 'ai-rank-suite')}</div>
									<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
										{result.identifiers.join(', ')} — fill these in under Schema → Identity.
									</p>
								</div>
								<div>
									<div className="t-overline mb-1.5">{__('Profiles to link (sameAs)', 'ai-rank-suite')}</div>
									<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
										{result.directories.join(', ')}
									</p>
								</div>
							</div>
							<div>
								<div className="t-overline mb-1.5">{__('FAQ questions that get quoted', 'ai-rank-suite')}</div>
								<ul className="m-0 pl-5 grid gap-1 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
									{result.faq.map((q, i) => (
										<li key={i}>{q}</li>
									))}
								</ul>
							</div>
						</div>
					</Card>
				</>
			)}
		</div>
	);
}
