import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { api } from '../api';
import { Button, Badge, Notice, Spinner, Bar, ScoreRing } from '../components/ui';
import { IconSparkle } from '../components/icons';
import KeywordSuggest from '../components/KeywordSuggest';

/**
 * The AI setup wizard.
 *
 * The standard wizard gets a site ready for search: licence, import, profile,
 * one key, discovery files, crawlers, first analysis. This one picks up where
 * it stops and puts the AI to work — in the order that pays off soonest, with
 * the AI doing the typing at each step and the person only choosing.
 *
 * Every step is backed by an endpoint that exists today, and every step is
 * skippable, so the wizard can never strand someone on a stage their site does
 * not need. It writes nothing until a step's own button is pressed.
 */

const STEPS = [
	{ id: 'engine', label: __('Engine', 'ai-rank-suite') },
	{ id: 'brief', label: __('Brief the AI', 'ai-rank-suite') },
	{ id: 'score', label: __('Score', 'ai-rank-suite') },
	{ id: 'describe', label: __('Descriptions', 'ai-rank-suite') },
	{ id: 'faq', label: __('FAQs', 'ai-rank-suite') },
	{ id: 'keywords', label: __('Keywords', 'ai-rank-suite') },
	{ id: 'prompts', label: __('AI prompts', 'ai-rank-suite') },
	{ id: 'routing', label: __('Routing', 'ai-rank-suite') },
	{ id: 'done', label: __('Done', 'ai-rank-suite') },
];

function Shell({ title, lede, children }) {
	return (
		<>
			<h2 className="m-0 text-[17px] font-medium">{title}</h2>
			{lede && (
				<p className="m-0 text-[13.5px]" style={{ color: 'var(--ars-ink-2)' }}>
					{lede}
				</p>
			)}
			{children}
		</>
	);
}

/** Drive one bulk job to completion from here, with a live bar. */
function BulkStep({ action, label, openCount, onDone }) {
	const [status, setStatus] = useState(null);
	const [busy, setBusy] = useState(false);
	const [error, setError] = useState(null);

	const run = async () => {
		setBusy(true);
		setError(null);
		try {
			let s = await api.post('/bulk/start', { action, scope: 'missing' });
			setStatus(s);
			s = await api.post('/bulk/tick');
			setStatus(s);
			while (s.state === 'running') {
				s = await api.post('/bulk/tick');
				setStatus(s);
			}
			onDone(s);
		} catch (e) {
			// "Nothing to process" is the server saying this step is already
			// done — a success in a 400's clothing.
			if (/nothing to process/i.test(e.message)) {
				setStatus({ state: 'done', done: 0, total: 0, progress: 100 });
				onDone({ state: 'done', done: 0 });
			} else {
				setError(e.message);
			}
		} finally {
			setBusy(false);
		}
	};

	const finished = status?.state === 'done';
	return (
		<div className="grid gap-3">
			{error && <Notice tone="serious">{error}</Notice>}
			{status && (
				<div className="grid gap-1.5">
					<div className="flex justify-between text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
						<span>
							{finished ? __('Finished', 'ai-rank-suite') : __('Working…', 'ai-rank-suite')} {(status.done || 0).toLocaleString()}
							{status.total ? ` ${__('of', 'ai-rank-suite')} ${status.total.toLocaleString()}` : ''}
							{status.failed ? ` · ${status.failed} ${__('failed', 'ai-rank-suite')}` : ''}
						</span>
						<span className="tabular-nums">{status.progress ?? 0}%</span>
					</div>
					<Bar value={status.progress ?? 0} />
				</div>
			)}
			{!finished && (
				<div className="flex items-center gap-3 flex-wrap">
					<Button onClick={run} busy={busy}>
						{label}
					</Button>
					{typeof openCount === 'number' && (
						<span className="t-caption">
							{openCount.toLocaleString()} {__('pages waiting', 'ai-rank-suite')}
						</span>
					)}
				</div>
			)}
			{finished && <Badge tone="good">✓ {__('Done', 'ai-rank-suite')}</Badge>}
		</div>
	);
}

export default function AiWizard({ onDone }) {
	const [index, setIndex] = useState(0);
	const [ready, setReady] = useState(false);
	const [error, setError] = useState(null);
	const [busy, setBusy] = useState(false);

	const [ai, setAi] = useState(null); // /settings/ai
	const [board, setBoard] = useState(null); // /ai/capabilities
	const [knowledge, setKnowledge] = useState(null); // /ai/knowledge
	const [notes, setNotes] = useState('');
	const [notesSaved, setNotesSaved] = useState(false);
	const [verify, setVerify] = useState(null);
	const [score, setScore] = useState(null);
	const [tracked, setTracked] = useState([]);
	const [vis, setVis] = useState(null);
	const [prompts, setPrompts] = useState([]);
	const [suggested, setSuggested] = useState(null);
	const [routing, setRouting] = useState(null);
	const [routeSaved, setRouteSaved] = useState(false);
	const [did, setDid] = useState({});

	useEffect(() => {
		Promise.allSettled([
			api.get('/settings/ai'),
			api.get('/ai/capabilities'),
			api.get('/ai/knowledge'),
			api.get('/rank/keywords'),
			api.get('/settings/ai-visibility'),
			api.get('/ai/routing'),
		]).then(([a, b, k, r, v, ro]) => {
			if (a.status === 'fulfilled') setAi(a.value);
			if (b.status === 'fulfilled') setBoard(b.value);
			if (k.status === 'fulfilled') {
				setKnowledge(k.value);
				setNotes(k.value.custom || '');
			}
			if (r.status === 'fulfilled') setTracked((r.value.keywords || []).map((x) => x.keyword));
			if (v.status === 'fulfilled') {
				setVis(v.value);
				setPrompts(v.value.settings?.prompts || v.value.prompts || []);
			}
			if (ro.status === 'fulfilled') setRouting(ro.value);
			setReady(true);
		});
	}, []);

	const step = STEPS[index].id;
	const next = () => {
		setError(null);
		setIndex((i) => Math.min(STEPS.length - 1, i + 1));
	};
	const back = () => setIndex((i) => Math.max(0, i - 1));

	const guard = async (fn) => {
		setBusy(true);
		setError(null);
		try {
			await fn();
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const rowOpen = (id) => {
		const r = (board?.rows || []).find((x) => x.id === id);
		return r && typeof r.open === 'number' ? r.open : null;
	};

	const refreshBoard = () => api.get('/ai/capabilities').then(setBoard).catch(() => {});

	if (!ready) {
		return (
			<div className="min-h-[60vh] grid place-items-center">
				<Spinner />
			</div>
		);
	}

	const connected = !!ai?.has_key;

	return (
		<div className="min-h-[80vh] grid place-items-center py-6 pr-5">
			<div className="ars-app w-full max-w-[720px] overflow-hidden">
				<div className="px-8 pt-8 pb-6" style={{ background: 'var(--ars-canvas)' }}>
					<div className="flex items-center gap-3">
						<span className="ars-brand-mark shrink-0" style={{ width: 44, height: 44, borderRadius: 12 }} aria-hidden>
							<IconSparkle width={24} height={24} style={{ color: '#fff' }} />
						</span>
						<div>
							<div className="text-[22px] font-medium leading-tight">
								<span className="ars-grad-text">{__('AI setup', 'ai-rank-suite')}</span>
							</div>
							<div className="text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>
								{__('Put the AI to work on this site — it types, you choose. Every step can be skipped.', 'ai-rank-suite')}
							</div>
						</div>
					</div>
					<div className="flex gap-1.5 mt-6" role="progressbar" aria-valuenow={index + 1} aria-valuemin={1} aria-valuemax={STEPS.length}>
						{STEPS.map((s, i) => (
							<div
								key={s.id}
								className="h-1 flex-1 ars-r-sm"
								style={{ background: i <= index ? 'var(--ars-brand)' : 'var(--ars-track)', transition: 'background 300ms cubic-bezier(0.2,0,0,1)' }}
								title={s.label}
							/>
						))}
					</div>
					<div className="t-caption mt-1.5">
						{__('Step', 'ai-rank-suite')} {index + 1} {__('of', 'ai-rank-suite')} {STEPS.length} · {STEPS[index].label}
					</div>
				</div>

				<div className="px-8 py-6 grid gap-4" style={{ background: 'var(--ars-surface)' }}>
					{step === 'engine' && (
						<Shell
							title={connected ? __('Your engine is connected', 'ai-rank-suite') : __('Connect an engine first', 'ai-rank-suite')}
							lede={
								connected
									? `${ai.key_hint ? `${__('Key', 'ai-rank-suite')} ${ai.key_hint} · ` : ''}${__('One test call proves it works before anything else in this wizard spends a token.', 'ai-rank-suite')}`
									: __('Everything after this step needs a model. Add a key on the AI Engine screen, then come back here.', 'ai-rank-suite')
							}
						>
							{connected ? (
								<div className="grid gap-3">
									{verify && <Notice tone={verify.ok ? 'good' : 'serious'}>{verify.message}</Notice>}
									<div className="flex items-center gap-2 flex-wrap">
										<Button
											variant="ghost"
											busy={busy}
											onClick={() =>
												guard(async () => {
													try {
														const r = await api.post('/ai/verify', {});
														setVerify({ ok: true, message: r.message || __('The engine answered.', 'ai-rank-suite') });
													} catch (e) {
														setVerify({ ok: false, message: e.message });
													}
												})
											}
										>
											{__('Test the connection', 'ai-rank-suite')}
										</Button>
										<Button onClick={next}>{__('Continue', 'ai-rank-suite')}</Button>
									</div>
								</div>
							) : (
								<div className="flex items-center gap-2 flex-wrap">
									<Button
										onClick={() => {
											// The lede above promises "then come back here", so
											// leave a crumb: the AI Engine screen reads this and
											// offers the way back. Session storage, because the
											// promise expires with the tab.
											try {
												window.sessionStorage.setItem('airanksuite-ai-wizard-return', '1');
											} catch {
												/* no storage: the jump still works, only the way back is manual */
											}
											window.location.hash = '/ai';
										}}
									>
										{__('Open AI Engine', 'ai-rank-suite')}
									</Button>
									<Button variant="ghost" onClick={next}>
										{__('Skip for now', 'ai-rank-suite')}
									</Button>
								</div>
							)}
						</Shell>
					)}

					{step === 'brief' && (
						<Shell
							title={__('Brief the AI about your business', 'ai-rank-suite')}
							lede={__(
								'The fixed template already tells every engine what this plugin is, what GEO means, the house rules and the facts WordPress knows about the site. This is the part only you can write — it is sent with every call, on every engine.',
								'ai-rank-suite'
							)}
						>
							<textarea
								rows={10}
								value={notes}
								placeholder={knowledge?.template || ''}
								onChange={(e) => {
									setNotes(e.target.value);
									setNotesSaved(false);
								}}
								style={{ fontFamily: 'inherit', fontSize: 13, lineHeight: 1.5 }}
							/>
							<div className="flex items-center justify-between gap-3 flex-wrap">
								<div className="flex items-center gap-2 flex-wrap">
									{!notes && knowledge?.template && (
										<Button variant="ghost" onClick={() => setNotes(knowledge.template)}>
											{__('Start from the template', 'ai-rank-suite')}
										</Button>
									)}
									{notesSaved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
								</div>
								<div className="flex items-center gap-2">
									<Button variant="ghost" onClick={next}>
										{__('Skip', 'ai-rank-suite')}
									</Button>
									<Button
										busy={busy}
										disabled={notes === (knowledge?.custom || '') && notesSaved}
										onClick={() =>
											guard(async () => {
												const k = await api.put('/ai/knowledge', { custom: notes });
												setKnowledge(k);
												setNotesSaved(true);
												setDid((d) => ({ ...d, brief: true }));
												next();
											})
										}
									>
										{__('Save and continue', 'ai-rank-suite')}
									</Button>
								</div>
							</div>
						</Shell>
					)}

					{step === 'score' && (
						<Shell
							title={__('Score every page', 'ai-rank-suite')}
							lede={__('Free and local — no AI call. Everything the AI does next reads from these scores, so they go first.', 'ai-rank-suite')}
						>
							<BulkStep
								action="analyze"
								label={__('Score the site', 'ai-rank-suite')}
								openCount={rowOpen('analyze')}
								onDone={async () => {
									setDid((d) => ({ ...d, score: true }));
									try {
										const s = await api.post('/score/recalculate');
										setScore(s.dimensions?.overall ?? null);
									} catch (e) {
										/* the ring is a nicety; the run itself succeeded */
									}
									refreshBoard();
								}}
							/>
							{score != null && (
								<div className="flex items-center gap-4">
									<ScoreRing value={score} size={84} onLight />
									<span className="text-[13px]" style={{ color: 'var(--ars-ink-2)' }}>
										{__('Site AI score right now. Watch it move as the next steps land.', 'ai-rank-suite')}
									</span>
								</div>
							)}
							<div className="flex items-center gap-2">
								<Button variant="ghost" onClick={back}>
									{__('Back', 'ai-rank-suite')}
								</Button>
								<Button onClick={next}>{did.score ? __('Continue', 'ai-rank-suite') : __('Skip', 'ai-rank-suite')}</Button>
							</div>
						</Shell>
					)}

					{step === 'describe' && (
						<Shell
							title={__('Write the missing meta descriptions', 'ai-rank-suite')}
							lede={__(
								'The highest-leverage thing the AI does. Every published page without a description gets one — 120–155 characters, grounded in the page, plus a summary an assistant can quote. Runs in slices; a large site finishes.',
								'ai-rank-suite'
							)}
						>
							{!connected && <Notice tone="warning">{__('Needs an engine — connect one on step 1.', 'ai-rank-suite')}</Notice>}
							{connected && (
								<BulkStep
									action="describe"
									label={__('Write them now', 'ai-rank-suite')}
									openCount={rowOpen('describe')}
									onDone={() => {
										setDid((d) => ({ ...d, describe: true }));
										refreshBoard();
									}}
								/>
							)}
							<div className="flex items-center gap-2">
								<Button variant="ghost" onClick={back}>
									{__('Back', 'ai-rank-suite')}
								</Button>
								<Button onClick={next}>{did.describe ? __('Continue', 'ai-rank-suite') : __('Skip', 'ai-rank-suite')}</Button>
							</div>
						</Shell>
					)}

					{step === 'faq' && (
						<Shell
							title={__('Generate FAQs', 'ai-rank-suite')}
							lede={__(
								'Three to six question-and-answer pairs per page, only from what the page already says, saved as FAQPage schema. The format assistants quote most readily.',
								'ai-rank-suite'
							)}
						>
							{!connected && <Notice tone="warning">{__('Needs an engine — connect one on step 1.', 'ai-rank-suite')}</Notice>}
							{connected && (
								<BulkStep
									action="faq"
									label={__('Generate FAQs now', 'ai-rank-suite')}
									openCount={rowOpen('faq')}
									onDone={() => {
										setDid((d) => ({ ...d, faq: true }));
										refreshBoard();
									}}
								/>
							)}
							<div className="flex items-center gap-2">
								<Button variant="ghost" onClick={back}>
									{__('Back', 'ai-rank-suite')}
								</Button>
								<Button onClick={next}>{did.faq ? __('Continue', 'ai-rank-suite') : __('Skip', 'ai-rank-suite')}</Button>
							</div>
						</Shell>
					)}

					{step === 'keywords' && (
						<Shell
							title={__('Choose keywords to track', 'ai-rank-suite')}
							lede={__(
								'The AI reads your published titles and proposes queries this site can realistically win. Pick the ones worth tracking; each becomes a row in the rank tracker.',
								'ai-rank-suite'
							)}
						>
							{!connected && <Notice tone="warning">{__('Needs an engine — connect one on step 1.', 'ai-rank-suite')}</Notice>}
							{connected && (
								<KeywordSuggest
									taken={tracked}
									onPick={(k) =>
										guard(async () => {
											await api.post('/rank/keywords', { keyword: k });
											setTracked((t) => [...t, k]);
											setDid((d) => ({ ...d, keywords: true }));
										})
									}
								/>
							)}
							{tracked.length > 0 && (
								<div className="flex items-center gap-2 flex-wrap">
									<Badge tone="good">
										{tracked.length} {__('tracked', 'ai-rank-suite')}
									</Badge>
									<span className="t-caption">{tracked.slice(-6).join(' · ')}</span>
								</div>
							)}
							<div className="flex items-center gap-2">
								<Button variant="ghost" onClick={back}>
									{__('Back', 'ai-rank-suite')}
								</Button>
								<Button onClick={next}>{did.keywords ? __('Continue', 'ai-rank-suite') : __('Skip', 'ai-rank-suite')}</Button>
							</div>
						</Shell>
					)}

					{step === 'prompts' && (
						<Shell
							title={__('Seed the AI answer test', 'ai-rank-suite')}
							lede={__(
								'The questions a person would ask ChatGPT or Perplexity that your site should be the answer to. The AI proposes them from your brand and content; the tracker then asks them on a schedule and records whether you are named.',
								'ai-rank-suite'
							)}
						>
							{!connected && <Notice tone="warning">{__('Needs an engine — connect one on step 1.', 'ai-rank-suite')}</Notice>}
							{connected && (
								<div className="grid gap-3">
									<div className="flex items-center gap-2 flex-wrap">
										<Button
											variant="ghost"
											busy={busy}
											onClick={() =>
												guard(async () => {
													const r = await api.post('/ai-visibility/suggest', { count: 10 });
													setSuggested(r.prompts || []);
												})
											}
										>
											<IconSparkle width={14} height={14} />
											{__('Suggest prompts with AI', 'ai-rank-suite')}
										</Button>
										{prompts.length > 0 && (
											<Badge tone="good">
												{prompts.length} {__('saved', 'ai-rank-suite')}
											</Badge>
										)}
									</div>
									{suggested && suggested.length === 0 && (
										<Notice tone="warning">{__('No usable prompts came back. Try again.', 'ai-rank-suite')}</Notice>
									)}
									{suggested && suggested.length > 0 && (
										<div className="ars-kwsuggest">
											{suggested.map((p) => {
												const done = prompts.includes(p);
												return (
													<button
														key={p}
														type="button"
														className={`ars-kwchip${done ? ' is-done' : ''}`}
														disabled={done}
														onClick={() =>
															guard(async () => {
																const nextPrompts = [...prompts, p];
																await api.put('/settings/ai-visibility', { ...(vis?.settings || {}), prompts: nextPrompts });
																setPrompts(nextPrompts);
																setDid((d) => ({ ...d, prompts: true }));
															})
														}
													>
														<span className="ars-kwchip-word">{p}</span>
														<Badge tone={done ? 'good' : 'neutral'}>{done ? __('added', 'ai-rank-suite') : __('add', 'ai-rank-suite')}</Badge>
													</button>
												);
											})}
										</div>
									)}
								</div>
							)}
							<div className="flex items-center gap-2">
								<Button variant="ghost" onClick={back}>
									{__('Back', 'ai-rank-suite')}
								</Button>
								<Button onClick={next}>{did.prompts ? __('Continue', 'ai-rank-suite') : __('Skip', 'ai-rank-suite')}</Button>
							</div>
						</Shell>
					)}

					{step === 'routing' && (
						<Shell
							title={__('One engine per job', 'ai-rank-suite')}
							lede={__(
								'Every job runs on your default engine unless you say otherwise. Most sites leave this alone; agencies point the cheap, high-volume jobs at a cheaper model. Change it any time under AI Autopilot.',
								'ai-rank-suite'
							)}
						>
							{routing && (routing.engines || []).length > 1 ? (
								<div className="grid gap-2">
									{(routing.jobs || []).map((job) => (
										<div key={job.id} className="flex items-center justify-between gap-3 flex-wrap">
											<span className="text-[13px] font-medium">{job.label}</span>
											<select
												value={job.assigned ? job.provider : ''}
												onChange={(e) => {
													const assignments = Object.fromEntries((routing.jobs || []).map((j) => [j.id, j.id === job.id ? e.target.value : j.assigned ? j.provider : '']));
													setRouting({
														...routing,
														jobs: routing.jobs.map((j) => (j.id === job.id ? { ...j, assigned: !!e.target.value, provider: e.target.value } : j)),
														_draft: assignments,
													});
													setRouteSaved(false);
												}}
											>
												<option value="">{__('Default engine', 'ai-rank-suite')}</option>
												{(routing.engines || []).map((e) => (
													<option key={e.id} value={e.id}>
														{e.label}
													</option>
												))}
											</select>
										</div>
									))}
									<div className="flex items-center gap-2 flex-wrap mt-1">
										{routeSaved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
									</div>
								</div>
							) : (
								<Notice tone="neutral">
									{__('Only one engine has a key, so every job already runs on it. Add a second key on the AI Engine screen to route jobs between them.', 'ai-rank-suite')}
								</Notice>
							)}
							<div className="flex items-center gap-2 flex-wrap">
								<Button variant="ghost" onClick={back}>
									{__('Back', 'ai-rank-suite')}
								</Button>
								{routing?._draft ? (
									<Button
										busy={busy}
										onClick={() =>
											guard(async () => {
												const b = await api.put('/ai/routing', { assignments: routing._draft, exclusive: !!routing.exclusive });
												setRouting(b);
												setRouteSaved(true);
												setDid((d) => ({ ...d, routing: true }));
												next();
											})
										}
									>
										{__('Save and continue', 'ai-rank-suite')}
									</Button>
								) : (
									<Button onClick={next}>{__('Continue', 'ai-rank-suite')}</Button>
								)}
							</div>
						</Shell>
					)}

					{step === 'done' && (
						<Shell
							title={__('The AI is set up', 'ai-rank-suite')}
							lede={__('Here is what it did in this session, and where each thing lives from now on.', 'ai-rank-suite')}
						>
							<ul className="m-0 pl-5 grid gap-1.5 text-[13px]" style={{ color: 'var(--ars-ink-2)' }}>
								<li>
									{did.brief ? '✓ ' : '– '}
									{__('Briefing saved — every engine reads it before every task.', 'ai-rank-suite')} <em>{__('AI Engine → Knowledge base', 'ai-rank-suite')}</em>
								</li>
								<li>
									{did.score ? '✓ ' : '– '}
									{__('Pages scored.', 'ai-rank-suite')} <em>{__('Dashboard → Full website analyzer', 'ai-rank-suite')}</em>
								</li>
								<li>
									{did.describe ? '✓ ' : '– '}
									{__('Meta descriptions written.', 'ai-rank-suite')} <em>{__('Content', 'ai-rank-suite')}</em>
								</li>
								<li>
									{did.faq ? '✓ ' : '– '}
									{__('FAQs generated.', 'ai-rank-suite')} <em>{__('Content · Schema', 'ai-rank-suite')}</em>
								</li>
								<li>
									{did.keywords ? '✓ ' : '– '}
									{__('Keywords tracked.', 'ai-rank-suite')} <em>{__('Search Console → Keywords', 'ai-rank-suite')}</em>
								</li>
								<li>
									{did.prompts ? '✓ ' : '– '}
									{__('Answer-test prompts saved.', 'ai-rank-suite')} <em>{__('AI Answer Simulation', 'ai-rank-suite')}</em>
								</li>
								<li>
									{did.routing ? '✓ ' : '– '}
									{__('Routing set.', 'ai-rank-suite')} <em>{__('AI Autopilot', 'ai-rank-suite')}</em>
								</li>
							</ul>
							<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>
								{__('Anything skipped is one button on the "Let AI do" panel — on the dashboard and on the AI Engine screen.', 'ai-rank-suite')}
							</p>
							<div className="flex items-center gap-2 flex-wrap">
								<Button onClick={onDone}>{__('Go to dashboard', 'ai-rank-suite')}</Button>
								<Button
									variant="ghost"
									onClick={() => {
										window.location.hash = '/autopilot';
										onDone();
									}}
								>
									{__('Open the autopilot', 'ai-rank-suite')}
								</Button>
							</div>
						</Shell>
					)}

					{error && <Notice tone="serious">{error}</Notice>}
				</div>
			</div>
		</div>
	);
}
