import React, { useEffect, useRef, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import ScreenVerdict from '../components/ScreenVerdict';
import Bing from './Bing';
import { Card, Button, Badge, Notice, Switch, Bar, Tabs, Panel, Advisor, PageState } from '../components/ui';
import RichResults from '../components/RichResults';

const VERIFY = [
	{ key: 'verify_google', label: __('Google Search Console', 'ai-rank-suite'), hint: __('The content value of the google-site-verification tag', 'ai-rank-suite') },
	{ key: 'verify_bing', label: __('Bing Webmaster Tools', 'ai-rank-suite'), hint: 'msvalidate.01' },
	{ key: 'verify_pinterest', label: __('Pinterest', 'ai-rank-suite'), hint: 'p:domain_verify' },
	{ key: 'verify_yandex', label: __('Yandex', 'ai-rank-suite'), hint: 'yandex-verification' },
	{ key: 'verify_baidu', label: __('Baidu', 'ai-rank-suite'), hint: __('baidu-site-verification — China’s biggest engine, and its AI answer layer', 'ai-rank-suite') },
	{ key: 'verify_naver', label: __('Naver', 'ai-rank-suite'), hint: __('naver-site-verification — the default engine in South Korea', 'ai-rank-suite') },
	{ key: 'verify_facebook', label: __('Meta / Facebook', 'ai-rank-suite'), hint: __('facebook-domain-verification — needed for catalogue and ad domains', 'ai-rank-suite') },
];

function IndexNow() {
	const [data, setData] = useState(null);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);
	const [urls, setUrls] = useState('');

	useEffect(() => {
		api.get('/settings/indexnow').then(setData).catch((e) => setError(e.message));
	}, []);

	if (!data) return <PageState error={error} />;
	const s = data.settings;
	const update = (patch) => setData({ ...data, settings: { ...s, ...patch } });

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

	const save = async () => {
		if (await run(() => api.put('/settings/indexnow', s))) {
			setSaved(true);
			setTimeout(() => setSaved(false), 2200);
		}
	};

	const list = urls
		.split(/[\n\s]+/)
		.map((u) => u.trim())
		.filter(Boolean);

	return (
		<>
			{error && <Notice tone="serious">{error}</Notice>}

			<Advisor
				tone={s.enabled ? 'good' : 'neutral'}
				text={
					s.enabled
						? __('IndexNow is active — Bing, Yandex, Seznam and Naver hear about a change the moment you make it.', 'ai-rank-suite')
						: __('IndexNow is switched off, so nothing is being submitted.', 'ai-rank-suite')
				}
				sub={
					s.enabled
						? (s.auto
							? sprintf(__('Covering %s, automatically on publish, update and unpublish.', 'ai-rank-suite'), (s.post_types || []).join(', ') || __('no post types', 'ai-rank-suite'))
							: sprintf(__('Covering %s — automatic submission is off, so this only happens when you press the button.', 'ai-rank-suite'), (s.post_types || []).join(', ') || __('no post types', 'ai-rank-suite')))
						: __('This needs no Google account and no API key. One switch in the settings below turns it on.', 'ai-rank-suite')
				}
			/>

			<Card title={__('Submit URLs now', 'ai-rank-suite')}>
				<div className="grid gap-3">
					<textarea
						rows={4}
						placeholder={`${window.airanksuiteData.homeUrl}my-page/\n${window.airanksuiteData.homeUrl}another-page/`}
						value={urls}
						onChange={(e) => setUrls(e.target.value)}
					/>
					<div className="flex items-center gap-2 flex-wrap">
						<Button
							onClick={async () => {
								if (await run(() => api.post('/indexnow/submit', { urls: list }))) setUrls('');
							}}
							busy={busy}
							disabled={!list.length}
						>
							{list.length
								? sprintf(_n('Submit %d URL', 'Submit %d URLs', list.length, 'ai-rank-suite'), list.length)
								: __('Submit URLs', 'ai-rank-suite')}
						</Button>
						<Button variant="ghost" onClick={() => run(() => api.post('/indexnow/submit', { scope: 'all' }))} busy={busy}>{__('Submit everything', 'ai-rank-suite')}</Button>
					</div>
					<p className="m-0 text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>
						{__('“Submit everything” sends your 500 most recent published URLs. Use it once after installing, then let the automatic submissions do the work.', 'ai-rank-suite')}
					</p>
				</div>
			</Card>

			{data.recent?.length > 0 && (
				<Card
					title={__('Recent submissions', 'ai-rank-suite')}
					subtitle={
						/* The log is append-only and a busy site fills it in a day.
						   Twenty rows of the same URL and the same 429 is not
						   twenty pieces of information — it is one, repeated. */
						(() => {
							const failed = data.recent.filter((r) => !r.ok).length;
							return failed > 0
								? sprintf(__('%1$d recent, %2$d rejected — a 429 means you submitted the same URL too often', 'ai-rank-suite'), data.recent.length, failed)
								: sprintf(__('%d recent, all accepted', 'ai-rank-suite'), data.recent.length);
						})()
					}
					action={<Badge tone={data.recent.some((r) => !r.ok) ? 'warning' : 'good'}>{data.recent.length}</Badge>}
				>
					<div className="ars-table-wrap"><table className="ars-table">
						<thead>
							<tr>
								<th>{__('URLs', 'ai-rank-suite')}</th>
								<th>{__('First URL', 'ai-rank-suite')}</th>
								<th>{__('Result', 'ai-rank-suite')}</th>
								<th>{__('When', 'ai-rank-suite')}</th>
							</tr>
						</thead>
						<tbody>
							{data.recent.slice(0, 12).map((r, i) => (
								<tr key={i}>
									<td className="tabular-nums">{r.count}</td>
									<td className="ars-mono" style={{ maxWidth: 300 }} title={String(r.first)}>
										<span className="ars-url">{String(r.first).replace(/^https?:\/\/[^/]+/, '')}</span>
									</td>
									<td>
										{r.ok ? (
											<Badge tone="good">✓ {r.code}</Badge>
										) : (
											<Badge tone="serious" title={r.error}>
												✕ {r.code || __('error', 'ai-rank-suite')}
											</Badge>
										)}
									</td>
									<td style={{ color: 'var(--ars-ink-3)' }}>{new Date(r.time * 1000).toLocaleString()}</td>
								</tr>
							))}
						</tbody>
					</table></div>
				</Card>
			)}
			<Panel
				title={__('IndexNow settings', 'ai-rank-suite')}
				note={s.enabled ? __('Active', 'ai-rank-suite') : __('Off', 'ai-rank-suite')}
				/* Open by default only while it is off, because then the switch
				   inside it is the whole task. Once it is running, this is a
				   form nobody needs to see again. */
				defaultOpen={!s.enabled}
			>
				<div className="grid gap-4">
				<Card
					title={__('IndexNow', 'ai-rank-suite')}
					subtitle={__('Instant indexing for Bing, Yandex, Seznam and Naver — no Google account or API key needed', 'ai-rank-suite')}
					action={s.enabled ? <Badge tone="good">✓ {__('Active', 'ai-rank-suite')}</Badge> : <Badge tone="neutral">{__('Off', 'ai-rank-suite')}</Badge>}
				>
					<div className="grid gap-4">
						{!data.permalinks && (
							<Notice tone="serious">
								{__('IndexNow needs pretty permalinks so the key file can be served. Switch Settings → Permalinks away from “Plain” first.', 'ai-rank-suite')}
							</Notice>
						)}

						<Switch
							checked={!!s.enabled}
							onChange={(v) => update({ enabled: v })}
							label={__('Enable IndexNow submissions', 'ai-rank-suite')}
						/>
						<Switch
							checked={!!s.auto}
							onChange={(v) => update({ auto: v })}
							label={__('Submit automatically when a page is published, updated or unpublished', 'ai-rank-suite')}
						/>

						<div className="flex gap-3 flex-wrap text-[13px]">
							{data.post_types.map((pt) => (
								<label key={pt} className="inline-flex items-center gap-1.5">
									<input
										type="checkbox"
										checked={s.post_types.includes(pt)}
										onChange={(e) =>
											update({
												post_types: e.target.checked
													? [...s.post_types, pt]
													: s.post_types.filter((x) => x !== pt),
											})
										}
									/>
									{pt}
								</label>
							))}
						</div>

						<div className="sm:max-w-[440px]">
							<label className="block font-medium mb-1">{__('Endpoint', 'ai-rank-suite')}</label>
							<select value={s.endpoint} onChange={(e) => update({ endpoint: e.target.value })}>
								{Object.entries(data.endpoints).map(([url, label]) => (
									<option key={url} value={url}>
										{label}
									</option>
								))}
							</select>
							<div className="text-[11.5px] mt-1" style={{ color: 'var(--ars-ink-3)' }}>{__('All participating engines share one network — the first option reaches every one of them.', 'ai-rank-suite')}</div>
						</div>

						<div className="flex items-center gap-2">
							<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
							{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
						</div>
					</div>
				</Card>

				<Card title={__('Your key file', 'ai-rank-suite')} subtitle={__('Search engines fetch this to prove the submissions come from you', 'ai-rank-suite')}>
					<div className="grid gap-3">
						<div className="flex items-center gap-2 flex-wrap">
							<a className="ars-mono text-[12.5px]" href={data.key_url} target="_blank" rel="noreferrer">
								{data.key_url}
							</a>
						</div>
						<div>
							<Button variant="ghost" onClick={() => run(() => api.post('/indexnow/key', {}))} busy={busy}>{__('Generate a new key', 'ai-rank-suite')}</Button>
						</div>
						<p className="m-0 text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Open the link — it must show the key as plain text. Regenerating invalidates the old key immediately.', 'ai-rank-suite')}</p>
					</div>
				</Card>

				</div>
			</Panel>

		</>
	);
}

export default function Google({ tab = 'indexing', onTab }) {
	const [data, setData] = useState(null);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);
	const [manualUrl, setManualUrl] = useState('');
	const [pastedKey, setPastedKey] = useState('');
	const fileRef = useRef(null);

	useEffect(() => {
		api.get('/settings/google').then(setData).catch((e) => setError(e.message));
	}, []);

	if (!data) return <PageState error={error} />;
	const s = data.settings;
	const update = (patch) => setData({ ...data, settings: { ...s, ...patch } });

	const save = async () => {
		setBusy(true);
		setError(null);
		try {
			setData(await api.put('/settings/google', s));
			setSaved(true);
			setTimeout(() => setSaved(false), 2200);
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	/*
	 * One path for both doors. The route has always taken the key as a string;
	 * the file is read into one before it is sent, so pasting needed no server
	 * change at all — only a field.
	 */
	const saveKey = async (json) => {
		setBusy(true);
		setError(null);
		try {
			setData(await api.post('/google/indexing/account', { json }));
			setPastedKey('');
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
			if (fileRef.current) fileRef.current.value = '';
		}
	};

	const uploadKey = async (file) => saveKey(await file.text());

	const removeKey = async () => {
		setBusy(true);
		try {
			setData(await api.del('/google/indexing/account'));
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const submitUrl = async () => {
		setBusy(true);
		setError(null);
		try {
			setData(await api.post('/google/indexing/submit', { url: manualUrl }));
			setManualUrl('');
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const idx = data.indexing;
	const quotaPct = Math.round((idx.used_today / idx.quota) * 100);

	return (
		<div className="ars-page">
			<Tabs
				tabs={[
					{ id: 'indexing', label: __('Google', 'ai-rank-suite') },
					{ id: 'rich', label: __('Rich results', 'ai-rank-suite') },
					{ id: 'bing', label: __('Bing', 'ai-rank-suite') },
					{ id: 'indexnow', label: __('IndexNow', 'ai-rank-suite') },
					{ id: 'verify', label: __('Verification', 'ai-rank-suite') },
				]}
				active={tab}
				onChange={onTab}
			/>

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

			{tab === 'indexing' && (
				<>
					<ScreenVerdict
						tone={idx.configured ? 'good' : 'neutral'}
						text={
							idx.configured
								? __('Google is told directly when a page is published, updated or removed.', 'ai-rank-suite')
								: __('Google is not told about changes directly — it finds them on its own schedule.', 'ai-rank-suite')
						}
						why={
							idx.configured
								? __('The Indexing API is Google\'s fast lane for job postings and live streams; for everything else the sitemap and IndexNow below carry the change.', 'ai-rank-suite')
								: __('A service account key from Google Cloud connects the Indexing API in three steps below. IndexNow (next tab) needs no account at all and covers Bing, Yandex, Seznam and Naver.', 'ai-rank-suite')
						}
					/>
					<Card
						title={__('Google Indexing API', 'ai-rank-suite')}
						subtitle={__('Tell Google directly when a page is published, updated or removed', 'ai-rank-suite')}
						action={idx.configured ? <Badge tone="good">✓ {__('Connected', 'ai-rank-suite')}</Badge> : <Badge tone="neutral">{__('Not connected', 'ai-rank-suite')}</Badge>}
					>
						{!idx.configured ? (
							<div className="grid gap-3">
								<ol className="m-0 pl-5 grid gap-2 text-[13px]">
									<li>
										{__('In', 'ai-rank-suite')}{' '}
										<a href="https://console.cloud.google.com/iam-admin/serviceaccounts" target="_blank" rel="noreferrer">{__('Google Cloud → Service Accounts', 'ai-rank-suite')}</a>
										{__(', create a service account and download its', 'ai-rank-suite')} <strong>{__('JSON key', 'ai-rank-suite')}</strong>.
									</li>
									<li>{__('Enable the', 'ai-rank-suite')} <strong>{__('Indexing API', 'ai-rank-suite')}</strong> {__('for that project (APIs & Services → Library).', 'ai-rank-suite')}
									</li>
									<li>
										{__('In', 'ai-rank-suite')}{' '}
										<a href="https://search.google.com/search-console/users" target="_blank" rel="noreferrer">{__('Search Console → Settings → Users and permissions', 'ai-rank-suite')}</a>
										{__(', add the service account\'s email address as an', 'ai-rank-suite')} <strong>{__('Owner', 'ai-rank-suite')}</strong> {__('of this property.', 'ai-rank-suite')}
									</li>
									<li>{__('Upload the JSON key here:', 'ai-rank-suite')}</li>
								</ol>
								{/*
								  * Two ways in, because the key arrives both ways.
								  * Google hands you a download, but by the time it
								  * reaches the person setting the site up it is
								  * usually a block of text in a message — and a
								  * screen that only takes a file makes them save
								  * the clipboard to disk first for no reason.
								  */}
								<div className="grid gap-2">
									<textarea
										className="ars-input ars-mono"
										rows={6}
										spellCheck={false}
										value={pastedKey}
										onChange={(e) => setPastedKey(e.target.value)}
										placeholder={'{\n  "type": "service_account",\n  "project_id": "…",\n  "client_email": "…",\n  "private_key": "-----BEGIN PRIVATE KEY-----…"\n}'}
										aria-label={__('Service account JSON', 'ai-rank-suite')}
									/>
									<div className="flex items-center gap-2 flex-wrap">
										<Button
											busy={busy}
											disabled={pastedKey.trim() === ''}
											onClick={() => saveKey(pastedKey)}
										>{__('Connect with this key', 'ai-rank-suite')}</Button>
										<span className="text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>{__('or', 'ai-rank-suite')}</span>
										<Button variant="ghost" onClick={() => fileRef.current?.click()} busy={busy}>{__('Choose the JSON file', 'ai-rank-suite')}</Button>
									</div>
									<input
										ref={fileRef}
										type="file"
										accept="application/json,.json"
										style={{ display: 'none' }}
										onChange={(e) => e.target.files?.[0] && uploadKey(e.target.files[0])}
									/>
								</div>
							</div>
						) : (
							<div className="grid gap-4">
								<div className="flex items-center justify-between gap-3 flex-wrap">
									<div className="text-[12.5px] ars-mono" style={{ color: 'var(--ars-ink-2)' }}>
										{idx.email}
									</div>
									<Button variant="danger" onClick={removeKey} busy={busy}>{__('Remove key', 'ai-rank-suite')}</Button>
								</div>

								<div className="grid gap-1.5">
									<div className="flex justify-between text-[12.5px]">
										<span className="font-medium">{__('Daily quota', 'ai-rank-suite')}</span>
										<span className="tabular-nums" style={{ color: 'var(--ars-ink-2)' }}>
											{sprintf(__('%1$s / %2$s URLs', 'ai-rank-suite'), idx.used_today, idx.quota)}
										</span>
									</div>
									<Bar value={quotaPct} />
								</div>

								<div className="grid gap-2">
									<Switch
										checked={!!s.indexing_auto}
										onChange={(v) => update({ indexing_auto: v })}
										label={__('Submit automatically when a page is published, updated or removed', 'ai-rank-suite')}
									/>
									<div className="flex gap-3 flex-wrap text-[13px]">
										{data.post_types.map((pt) => (
											<label key={pt.slug} className="inline-flex items-center gap-1.5">
												<input
													type="checkbox"
													checked={s.indexing_types.includes(pt.slug)}
													onChange={(e) =>
														update({
															indexing_types: e.target.checked
																? [...s.indexing_types, pt.slug]
																: s.indexing_types.filter((x) => x !== pt.slug),
														})
													}
												/>
												{pt.label}
											</label>
										))}
									</div>
									<div className="flex items-center gap-2">
										<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
										{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
									</div>
								</div>

								<div className="grid gap-2">
									<label className="font-medium">{__('Submit a single URL now', 'ai-rank-suite')}</label>
									<div className="flex gap-2">
										<input
											type="text"
											placeholder={`${window.airanksuiteData.homeUrl}my-page/`}
											value={manualUrl}
											onChange={(e) => setManualUrl(e.target.value)}
										/>
										<Button onClick={submitUrl} busy={busy} disabled={!manualUrl}>{__('Submit', 'ai-rank-suite')}</Button>
									</div>
								</div>

								<Notice>
									{__('Google officially supports the Indexing API for job postings and livestream pages. Other page types are commonly submitted too, but Google does not guarantee they will be crawled faster.', 'ai-rank-suite')}
								</Notice>
							</div>
						)}
					</Card>

					{idx.recent?.length > 0 && (
						<Card title={__('Recent submissions', 'ai-rank-suite')}>
							<div className="ars-table-wrap"><table className="ars-table">
								<thead>
									<tr>
										<th>{__('URL', 'ai-rank-suite')}</th>
										<th>{__('Type', 'ai-rank-suite')}</th>
										<th>{__('Result', 'ai-rank-suite')}</th>
										<th>{__('When', 'ai-rank-suite')}</th>
									</tr>
								</thead>
								<tbody>
									{idx.recent.slice(0, 15).map((r, i) => (
										<tr key={i}>
											<td className="ars-mono" style={{ maxWidth: 320 }} title={r.url}>
												<span className="ars-url">{r.url.replace(/^https?:\/\/[^/]+/, '')}</span>
											</td>
											<td style={{ color: 'var(--ars-ink-3)' }}>{r.type === 'URL_DELETED' ? __('Removed', 'ai-rank-suite') : __('Updated', 'ai-rank-suite')}</td>
											<td>
												{r.ok ? (
													<Badge tone="good">✓ {__('Sent', 'ai-rank-suite')}</Badge>
												) : (
													<Badge tone="serious" title={r.error}>
														✕ {__('Failed', 'ai-rank-suite')}
													</Badge>
												)}
											</td>
											<td style={{ color: 'var(--ars-ink-3)' }}>
												{new Date(r.time * 1000).toLocaleString()}
											</td>
										</tr>
									))}
								</tbody>
							</table></div>
						</Card>
					)}
				</>
			)}

			{tab === 'rich' && <RichResults />}
			{tab === 'bing' && <Bing />}
			{tab === 'indexnow' && <IndexNow />}

			{tab === 'verify' && (
				<Card
					title={__('Site verification', 'ai-rank-suite')}
					subtitle={__('Verification tags are output on your home page only — that is all these services read', 'ai-rank-suite')}
					action={saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
				>
					<div className="grid gap-3">
						{VERIFY.map((v) => (
							<div key={v.key}>
								<label className="block font-medium mb-1">{v.label}</label>
								<input
									type="text"
									placeholder={v.hint}
									value={s[v.key] || ''}
									onChange={(e) => update({ [v.key]: e.target.value })}
								/>
							</div>
						))}
						<div>
							<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
						</div>
						<p className="m-0 text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Paste only the content value, not the whole meta tag — the plugin builds the tag for you.', 'ai-rank-suite')}</p>
					</div>
				</Card>
			)}
		</div>
	);
}
