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

const MODES = [
	{
		id: 'auto',
		label: __('Automatic', 'ai-rank-suite'),
		note: __('Detect what is installed and pick the safe option. Recommended.', 'ai-rank-suite'),
	},
	{
		id: 'geo',
		label: __('GEO layer only', 'ai-rank-suite'),
		note: __('Your current SEO plugin keeps titles, descriptions and canonicals. We add the AI layer on top.', 'ai-rank-suite'),
	},
	{
		id: 'solo',
		label: __('Take over', 'ai-rank-suite'),
		note: __('AI Rank Suite owns every tag. Whatever else writes them — named plugin or not — its copy is stripped from the page.', 'ai-rank-suite'),
	},
	{
		id: 'manual',
		label: __('Per tag', 'ai-rank-suite'),
		note: __('Decide surface by surface who writes what.', 'ai-rank-suite'),
	},
];

const OWNERS = [
	{ id: 'airs', label: __('AI Rank Suite', 'ai-rank-suite') },
	{ id: 'other', label: __('Other plugin', 'ai-rank-suite') },
	{ id: 'both', label: __('Both', 'ai-rank-suite') },
];

export default function Coexistence() {
	const [data, setData] = useState(null);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);
	const [scan, setScan] = useState(null);
	const [scanning, setScanning] = useState(false);

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

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

	const s = data.settings;
	const other = data.primary;

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

	const runScan = async () => {
		setScanning(true);
		setError(null);
		try {
			const result = await api.post('/coexistence/scan', {});
			setScan(result);
			// The scan is what decides whether an unnamed writer exists, so the
			// card above has to hear about it — otherwise its verdict is one
			// scan out of date.
			setData((d) => (d ? { ...d, unknown: !!result.unknown } : d));
		} catch (e) {
			setError(e.message);
		} finally {
			setScanning(false);
		}
	};

	return (
		<div className="ars-page">
			<Card
				title={__('Coexistence', 'ai-rank-suite')}
				subtitle={__('Keep the SEO plugin you already trust. Add the AI layer without a single duplicate tag.', 'ai-rank-suite')}
				action={
					other ? (
						<Badge tone="warning">
							{other.label} {other.version}
						</Badge>
					) : data.unknown ? (
						<Badge tone="warning">{__('Something else writes tags', 'ai-rank-suite')}</Badge>
					) : (
						<Badge tone="good">{__('No other SEO plugin', 'ai-rank-suite')}</Badge>
					)
				}
			>
				<div className="grid gap-4">
					{/*
					  * Three states, not two. The green "nothing else is writing
					  * tags" used to appear whenever we could not *name* a
					  * competitor — which is exactly the site where an unnamed
					  * one is writing a second canonical, and the screen was
					  * telling the customer everything was fine.
					  */}
					{other ? (
						<Notice tone="info">
							<strong>{other.label}</strong>{' '}
							{sprintf(__('is active and writes %d of the same tags we do. Pick who owns what below — nothing is duplicated either way.', 'ai-rank-suite'), other.surfaces.length)}
						</Notice>
					) : data.unknown ? (
						<Notice tone="warning">
							{__('The last scan found SEO tags on this site that are not ours, from something we cannot name — a white-labelled build, a theme with its own SEO fields, or code in functions.php. AI Rank Suite owns every tag and strips the other copy, so the page still has exactly one of each. Run the scan again below to confirm.', 'ai-rank-suite')}
						</Notice>
					) : (
						<Notice tone="good">
							{__('Nothing else is writing SEO tags on this site, so AI Rank Suite owns everything. Install another SEO plugin later and this screen switches to safe mode by itself.', 'ai-rank-suite')}
						</Notice>
					)}

					<div>
						<label className="block font-medium mb-2">{__('Mode', 'ai-rank-suite')}</label>
						<div className="grid gap-2 sm:grid-cols-2">
							{MODES.map((m) => (
								<button
									key={m.id}
									type="button"
									onClick={() => put({ mode: m.id })}
									className={`ars-pick${s.mode === m.id ? ' is-active' : ''}`}
								>
									<span className="ars-pick-title">
										{m.label}
										{s.mode === m.id && <span style={{ marginLeft: 'auto', color: 'var(--ars-brand)' }}>✓</span>}
									</span>
									<span className="ars-pick-note">{m.note}</span>
								</button>
							))}
						</div>
					</div>

					<Switch
						checked={!!s.enforce}
						onChange={(v) => put({ enforce: v })}
						label={__('Enforce on the rendered page (duplicate-tag firewall)', 'ai-rank-suite')}
					/>

					<Explain title={__('How the firewall works', 'ai-rank-suite')}>
						<p>
							{__('Deciding who', 'ai-rank-suite')} <em>{__('should', 'ai-rank-suite')}</em>{' '}
							{__('write a tag is not enough — plugins hook', 'ai-rank-suite')} <code>wp_head</code>{' '}
							{__('at every priority, and some write from the theme. So the page itself is checked: the head is captured as it renders, split into “ours” and “everything else”, and whichever copy does not own that surface is removed before the browser sees it.', 'ai-rank-suite')}
						</p>
						<p>
							{__('The result is exactly one canonical, one description and one JSON-LD graph — whoever wrote them. Turn this off only if you want to inspect the raw output of both plugins.', 'ai-rank-suite')}
						</p>
					</Explain>

					{error && <Notice tone="serious">{error}</Notice>}
					{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
				</div>
			</Card>

			<Card
				title={__('Who owns which tag', 'ai-rank-suite')}
				subtitle={
					s.mode === 'manual'
						? __('Your choices, applied exactly', 'ai-rank-suite')
						: sprintf(__('Derived from the “%s” mode — switch to Per tag to edit', 'ai-rank-suite'), MODES.find((m) => m.id === s.mode)?.label)
				}
			>
				<div className="grid gap-2">
					{data.surfaces.map((surface) => {
						const owner = data.effective[surface.id] || 'airs';
						return (
							<div
								key={surface.id}
								className="flex items-center justify-between gap-4 px-3 py-2.5 flex-wrap"
								style={{ background: 'var(--ars-surface-2)', borderRadius: 'var(--ars-r-sm)' }}
							>
								<div className="min-w-[220px]">
									<div className="font-semibold text-[13px]">{surface.label}</div>
									<div className="text-[11.5px] mt-0.5" style={{ color: 'var(--ars-ink-3)' }}>
										{surface.desc}
									</div>
								</div>
								{s.mode === 'manual' ? (
									<Segmented
										value={owner}
										onChange={(v) => put({ ownership: { ...data.effective, [surface.id]: v } })}
										options={OWNERS.map((o) => ({
											id: o.id,
											label: o.id === 'other' && other ? other.label : o.label,
										}))}
									/>
								) : (
									<Badge tone={owner === 'airs' ? 'good' : owner === 'both' ? 'warning' : 'neutral'}>
										{owner === 'airs' ? 'AI Rank Suite' : owner === 'both' ? __('Both (not deduplicated)', 'ai-rank-suite') : other?.label || __('Other plugin', 'ai-rank-suite')}
									</Badge>
								)}
							</div>
						);
					})}
				</div>
			</Card>

			<Card
				title={__('Live conflict scan', 'ai-rank-suite')}
				subtitle={__('Fetches your home page and counts every tag actually rendered — proof, not a promise', 'ai-rank-suite')}
				action={
					<Button variant="ghost" busy={scanning} onClick={runScan}>{__('Run scan', 'ai-rank-suite')}</Button>
				}
			>
				{!scan ? (
					<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>
						{__('Run the scan after changing anything above. It requests one page as an anonymous visitor and reports what the browser would receive.', 'ai-rank-suite')}
					</p>
				) : (
					<div className="grid gap-3">
						{scan.clean ? (
							<Notice tone="good">{__('No duplicate tags. Both plugins are running side by side cleanly.', 'ai-rank-suite')}</Notice>
						) : (
							<Notice tone="warning">
								{sprintf(_n('%d surface is written by both plugins. Turn the firewall on, or hand those surfaces to one owner.', '%d surfaces are written by both plugins. Turn the firewall on, or hand those surfaces to one owner.', scan.duplicates, 'ai-rank-suite'), scan.duplicates)}
							</Notice>
						)}
						<div className="ars-table-wrap"><table className="ars-table">
							<thead>
								<tr>
									<th>{__('Tag', 'ai-rank-suite')}</th>
									<th style={{ textAlign: 'right' }}>{__('From us', 'ai-rank-suite')}</th>
									<th style={{ textAlign: 'right' }}>{__('From others', 'ai-rank-suite')}</th>
									<th style={{ textAlign: 'right' }}>{__('Status', 'ai-rank-suite')}</th>
								</tr>
							</thead>
							<tbody>
								{scan.rows.map((r) => (
									<tr key={r.id}>
										<td>{r.label}</td>
										<td style={{ textAlign: 'right' }}>{r.ours}</td>
										<td style={{ textAlign: 'right' }}>{r.theirs}</td>
										<td style={{ textAlign: 'right' }}>
											{r.clash ? <Badge tone="serious">{__('Duplicated', 'ai-rank-suite')}</Badge> : <Badge tone="good">{__('Clean', 'ai-rank-suite')}</Badge>}
										</td>
									</tr>
								))}
							</tbody>
						</table></div>
					</div>
				)}
			</Card>

			{data.detected.length > 0 && (
				<Card title={__('Detected on this site', 'ai-rank-suite')} subtitle={__('Everything that writes SEO or social tags', 'ai-rank-suite')}>
					<div className="grid gap-2">
						{data.detected.map((p) => (
							<div key={p.id} className="flex items-center justify-between gap-3 flex-wrap">
								<div className="font-medium text-[13px]">
									{p.label} {p.version && <span style={{ color: 'var(--ars-ink-3)' }}>{p.version}</span>}
								</div>
								<div className="text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>
									{__('writes:', 'ai-rank-suite')} {p.surfaces.join(', ')}
								</div>
							</div>
						))}
					</div>
				</Card>
			)}
		</div>
	);
}
