import React, { useEffect, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import ScreenVerdict from '../components/ScreenVerdict';
import Htaccess from './Htaccess';
import { Card, Button, Switch, Badge, Notice, Tabs, PageState, CodeBlock, MetricGrid, Progress } from '../components/ui';
import { IconExternal } from '../components/icons';

function useSettings(endpoint) {
	const [data, setData] = useState(null);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);

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

	const update = (patch) => setData((d) => ({ ...d, settings: { ...d.settings, ...patch } }));

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

	return { data, update, save, busy, saved, error };
}

function Robots() {
	const { data, update, save, busy, saved, error } = useSettings('/settings/robots');
	if (!data) return <PageState error={error} />;
	const s = data.settings;

	const ARCHIVES = [
		{ key: 'noindex_author', label: __('Author archives', 'ai-rank-suite'), hint: __('Usually duplicate content on single-author sites', 'ai-rank-suite') },
		{ key: 'noindex_date', label: __('Date archives', 'ai-rank-suite'), hint: __('Rarely useful as search results', 'ai-rank-suite') },
		{ key: 'noindex_search', label: __('Internal search results', 'ai-rank-suite'), hint: __('Google explicitly discourages indexing these', 'ai-rank-suite') },
		{ key: 'noindex_attachment', label: __('Attachment pages', 'ai-rank-suite'), hint: __('Thin pages that only hold one media file', 'ai-rank-suite') },
		{ key: 'noindex_paginated', label: __('Paginated archive pages', 'ai-rank-suite'), hint: __('Page 2, 3, … of an archive', 'ai-rank-suite') },
	];

	const onCount = ARCHIVES.filter((a) => !!s[a.key]).length;
	const verdict = {
		tone: onCount === 0 ? 'warning' : 'good',
		text:
			onCount === 0
				? __('Every archive type is left indexable — search engines can spend their crawl on author, date and search pages.', 'ai-rank-suite')
				: s.robots_txt_enabled
					? sprintf(__('%1$d of %2$d archive types are set to noindex and custom robots.txt rules are on.', 'ai-rank-suite'), onCount, ARCHIVES.length)
					: sprintf(__('%1$d of %2$d archive types are set to noindex.', 'ai-rank-suite'), onCount, ARCHIVES.length),
		why:
			onCount === 0
				? __('Author, date, search and attachment archives are the pages nobody wants to rank; noindexing them keeps the crawl on the pages that matter.', 'ai-rank-suite')
				: __('Blocked archives keep the crawl on real content. Anything here changes robots meta on the next request — no cache purge needed beyond the plugin\'s own.', 'ai-rank-suite'),
	};
	return (
		<div className="grid gap-4">
			{error && <Notice tone="serious">{error}</Notice>}
			<ScreenVerdict {...verdict} />
			<Card
				title={__('Indexing rules for archives', 'ai-rank-suite')}
				subtitle={__('Keep thin, duplicated pages out of search results and AI training sets', 'ai-rank-suite')}
				action={saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
			>
				<div className="grid gap-3">
					{ARCHIVES.map((a) => (
						<div key={a.key} className="flex items-start justify-between gap-4">
							<div>
								<div className="font-medium">{sprintf(__('Set %s to noindex', 'ai-rank-suite'), a.label)}</div>
								<div className="text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>
									{a.hint}
								</div>
							</div>
							<Switch checked={!!s[a.key]} onChange={(v) => update({ [a.key]: v })} />
						</div>
					))}

					<div className="grid gap-3 sm:grid-cols-2 mt-1">
						<div>
							<label className="block font-medium mb-1">{__('Max snippet length', 'ai-rank-suite')}</label>
							<input
								type="number"
								value={s.max_snippet}
								onChange={(e) => update({ max_snippet: Number(e.target.value) })}
							/>
							<div className="text-[12px] mt-1" style={{ color: 'var(--ars-ink-3)' }}>
								{__('-1 = no limit (recommended)', 'ai-rank-suite')}
							</div>
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Max image preview', 'ai-rank-suite')}</label>
							<select value={s.max_image_preview} onChange={(e) => update({ max_image_preview: e.target.value })}>
								<option value="large">large</option>
								<option value="standard">standard</option>
								<option value="none">none</option>
							</select>
						</div>
					</div>

					<div>
						<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
					</div>
				</div>
			</Card>

			<Card
				title="robots.txt"
				subtitle={__('Custom rules are appended after the AI crawler block', 'ai-rank-suite')}
				action={
					<Switch
						checked={!!s.robots_txt_enabled}
						onChange={(v) => update({ robots_txt_enabled: v })}
						label={__('Enable custom rules', 'ai-rank-suite')}
					/>
				}
			>
				{data.physical_robots_txt && (
					<div className="mb-3">
						<Notice tone="serious">{__('A physical', 'ai-rank-suite')} <code>robots.txt</code> {__('file exists on your server and overrides everything here. Delete it so WordPress can serve robots.txt dynamically.', 'ai-rank-suite')}
						</Notice>
					</div>
				)}
				<textarea
					rows={8}
					className="ars-mono"
					placeholder={'User-agent: *\nDisallow: /private/'}
					value={s.robots_txt_custom}
					onChange={(e) => update({ robots_txt_custom: e.target.value })}
					disabled={!s.robots_txt_enabled}
				/>
				<div className="flex items-center gap-3 mt-2">
					<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
					<a href={data.robots_url} target="_blank" rel="noreferrer" className="text-[12.5px] inline-flex items-center gap-1">{__('View robots.txt', 'ai-rank-suite')}<IconExternal size={11} />
					</a>
				</div>
			</Card>
		</div>
	);
}

function Breadcrumbs() {
	const { data, update, save, busy, saved, error } = useSettings('/settings/breadcrumbs');
	if (!data) return <PageState error={error} />;
	const s = data.settings;

	return (
		<div className="grid gap-4">
			{error && <Notice tone="serious">{error}</Notice>}
			<Card
				title={__('Breadcrumbs', 'ai-rank-suite')}
				subtitle={__('Shown via the [airanksuite_breadcrumbs] shortcode — and always emitted as BreadcrumbList schema', 'ai-rank-suite')}
				action={
					<div className="flex items-center gap-2">
						{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
						<Switch checked={!!s.enabled} onChange={(v) => update({ enabled: v })} label={__('Enabled', 'ai-rank-suite')} />
					</div>
				}
			>
				<div className="grid gap-4">
					<div className="ars-r-md px-4 py-3" style={{ background: 'var(--ars-surface-2)' }}>
						<div className="text-[11px] font-semibold mb-1.5" style={{ color: 'var(--ars-ink-3)' }}>{__('PREVIEW', 'ai-rank-suite')}</div>
						<div className="text-[13px]">
							{s.prefix && <span style={{ color: 'var(--ars-ink-3)' }}>{s.prefix} </span>}
							{data.preview.map((label, i) => (
								<span key={i}>
									{i > 0 && <span style={{ color: 'var(--ars-ink-3)' }}> {s.separator} </span>}
									<span style={{ color: i === data.preview.length - 1 ? 'var(--ars-ink)' : 'var(--ars-brand)' }}>
										{label}
									</span>
								</span>
							))}
						</div>
					</div>

					<div className="grid gap-3 sm:grid-cols-2">
						<div>
							<label className="block font-medium mb-1">{__('Home label', 'ai-rank-suite')}</label>
							<input
								type="text"
								placeholder={__('Home', 'ai-rank-suite')}
								value={s.home_label}
								onChange={(e) => update({ home_label: e.target.value })}
							/>
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Separator', 'ai-rank-suite')}</label>
							<input type="text" value={s.separator} onChange={(e) => update({ separator: e.target.value })} />
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Prefix (optional)', 'ai-rank-suite')}</label>
							<input
								type="text"
								placeholder={__('You are here:', 'ai-rank-suite')}
								value={s.prefix}
								onChange={(e) => update({ prefix: e.target.value })}
							/>
						</div>
					</div>

					<Switch
						checked={!!s.show_current}
						onChange={(v) => update({ show_current: v })}
						label={__('Show the current page as the last crumb', 'ai-rank-suite')}
					/>

					<div className="flex items-center gap-2">
						<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
					</div>

					<div className="text-[12px] grid gap-1" style={{ color: 'var(--ars-ink-3)' }}>
						<span>{__('Shortcode:', 'ai-rank-suite')}<code className="ars-mono">[airanksuite_breadcrumbs]</code>
						</span>
						<span>
							{__('In a theme template:', 'ai-rank-suite')}{' '}
							<code className="ars-mono">{'<?php echo do_shortcode( \'[airanksuite_breadcrumbs]\' ); ?>'}</code>
						</span>
					</div>
				</div>
			</Card>
		</div>
	);
}

/**
 * The media library, counted, and the one job that fixes most of it.
 *
 * The settings below decide what a *new* image gets. This is about the
 * images already there: how many say nothing, how many are the size of a
 * poster, and a button that writes the missing alt texts from the template
 * in one run, fifty at a time, with the bar moving.
 */
function MediaAudit() {
	const [audit, setAudit] = useState(null);
	const [error, setError] = useState(null);
	const [job, setJob] = useState(null);
	const load = (fresh = false) => api.get(`/image-seo/audit${fresh ? '?fresh=1' : ''}`).then(setAudit).catch((e) => setError(e.message));
	useEffect(() => {
		load();
	}, []);
	const fill = async () => {
		setError(null);
		const total = audit?.no_alt || 0;
		let offset = 0;
		let filled = 0;
		let skipped = 0;
		setJob({ filled, skipped, total, done: false });
		try {
			for (;;) {
				const r = await api.post('/image-seo/fill', { offset });
				filled += r.filled;
				skipped += r.skipped;
				offset = r.offset;
				setJob({ filled, skipped, total, done: r.done });
				if (r.done) break;
			}
			await load(true);
		} catch (e) {
			setError(e.message);
			setJob(null);
		}
	};
	if (error) return <Notice tone="serious">{error}</Notice>;
	if (!audit) return <Card>{__('Counting the media library…', 'ai-rank-suite')}</Card>;
	const kb = (b) => (b >= 1024 * 1024 ? `${(b / 1024 / 1024).toFixed(1)} MB` : `${Math.round(b / 1024)} KB`);
	return (
		<Card
			title={__('Media library', 'ai-rank-suite')}
			subtitle={audit.sampled ? __('Dimensions and weight read for the newest 5,000 images.', 'ai-rank-suite') : __('Every image attachment on this site, counted.', 'ai-rank-suite')}
			action={<Button variant="ghost" onClick={() => load(true)}>{__('Recount', 'ai-rank-suite')}</Button>}
		>
			<div className="grid gap-3">
				<MetricGrid
					columns={4}
					metrics={[
						{ id: 'total', label: __('Images', 'ai-rank-suite'), value: Number(audit.total).toLocaleString() },
						{ id: 'no_alt', label: __('Without alt text', 'ai-rank-suite'), value: Number(audit.no_alt).toLocaleString(), accent: audit.no_alt ? 'var(--ars-warning)' : 'var(--ars-good)', hint: __('Read by screen readers, image search and multimodal assistants. An empty alt is an image that says nothing.', 'ai-rank-suite') },
						{ id: 'oversized', label: __('Wider than 2500 px', 'ai-rank-suite'), value: Number(audit.oversized).toLocaleString(), accent: audit.oversized ? 'var(--ars-warning)' : 'var(--ars-good)', hint: __('Bigger than any screen shows. Resize before upload; the page loads faster and image search prefers it.', 'ai-rank-suite') },
						{ id: 'heavy', label: __('Heavier than 500 KB', 'ai-rank-suite'), value: Number(audit.heavy).toLocaleString(), accent: audit.heavy ? 'var(--ars-warning)' : 'var(--ars-good)' },
					]}
				/>
				{job ? (
					<Progress
						label={job.done ? __('Done', 'ai-rank-suite') : __('Writing alt texts…', 'ai-rank-suite')}
						done={Math.min(job.total, job.filled + job.skipped)}
						total={job.total}
						note={sprintf(
							/* translators: 1: filled, 2: skipped. */
							__('%1$s written, %2$s skipped because the template and the image gave nothing to say', 'ai-rank-suite'),
							Number(job.filled).toLocaleString(),
							Number(job.skipped).toLocaleString()
						)}
					/>
				) : (
					<div className="flex items-center gap-3 flex-wrap">
						<Button onClick={fill} disabled={!audit.no_alt}>{sprintf(__('Write alt text for %s images from the template', 'ai-rank-suite'), Number(audit.no_alt).toLocaleString())}</Button>
						<span className="text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>{sprintf(__('Template: %s. Existing alt texts are never touched.', 'ai-rank-suite'), audit.template || '%filename%')}</span>
					</div>
				)}
				{audit.largest && audit.largest.length > 0 && (
					<div>
						<div className="text-[11px] font-semibold uppercase tracking-wide mb-1.5" style={{ color: 'var(--ars-ink-3)' }}>{__('Largest images', 'ai-rank-suite')}</div>
						<ul className="m-0 p-0 grid gap-1" style={{ listStyle: 'none' }}>
							{audit.largest.map((img) => (
								<li key={img.id} className="flex items-center justify-between gap-3 text-[12.5px]">
									<a href={img.edit} target="_blank" rel="noreferrer" className="truncate">{img.title || `#${img.id}`}</a>
									<span className="tabular-nums" style={{ color: 'var(--ars-ink-3)' }}>{img.width} × {img.height} px{img.bytes ? ` · ${kb(img.bytes)}` : ''}</span>
								</li>
							))}
						</ul>
					</div>
				)}
			</div>
		</Card>
	);
}

function Images() {
	const { data, update, save, busy, saved, error } = useSettings('/settings/image-seo');
	if (!data) return <PageState error={error} />;
	const s = data.settings;

	return (
		<div className="grid gap-4">
			{error && <Notice tone="serious">{error}</Notice>}
			<MediaAudit />
			<Card title={__('Image SEO', 'ai-rank-suite')} subtitle={__('Fill missing alt text automatically — good for search, required for accessibility', 'ai-rank-suite')} action={saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}>
				<div className="grid gap-3">
					<Switch checked={!!s.auto_alt} onChange={(v) => update({ auto_alt: v })} label={__('Add alt text when an image has none', 'ai-rank-suite')} />
					<Switch checked={!!s.auto_title} onChange={(v) => update({ auto_title: v })} label={__('Add title attribute when missing', 'ai-rank-suite')} />
					<div>
						<label className="block font-medium mb-1">{__('Alt text template', 'ai-rank-suite')}</label>
						<input type="text" value={s.alt_template} onChange={(e) => update({ alt_template: e.target.value })} />
						<div className="text-[12px] mt-1.5 flex flex-wrap gap-1.5" style={{ color: 'var(--ars-ink-3)' }}>
							{['%filename%', '%title%', '%caption%', '%postname%', '%sitename%'].map((v) => (
								<code key={v} className="ars-mono px-1.5 py-0.5 rounded" style={{ background: 'var(--ars-surface-2)' }}>
									{v}
								</code>
							))}
						</div>
					</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)' }}>{__('Existing alt texts are never overwritten — this only fills gaps.', 'ai-rank-suite')}</p>
				</div>
			</Card>

			<Card title={__('Outbound links', 'ai-rank-suite')} subtitle={__('How links to other websites are treated', 'ai-rank-suite')}>
				<div className="grid gap-3">
					<Switch
						checked={!!s.link_nofollow}
						onChange={(v) => update({ link_nofollow: v })}
						label={__('Add rel="nofollow" to external links', 'ai-rank-suite')}
					/>
					<Switch
						checked={!!s.link_new_tab}
						onChange={(v) => update({ link_new_tab: v })}
						label={__('Open external links in a new tab', 'ai-rank-suite')}
					/>
					<div>
						<label className="block font-medium mb-1">{__('Never touch these domains (one per line)', 'ai-rank-suite')}</label>
						<textarea
							rows={3}
							className="ars-mono"
							placeholder={'partner.com\naffiliate-network.com'}
							value={s.link_exclude}
							onChange={(e) => update({ link_exclude: e.target.value })}
						/>
					</div>
					<div>
						<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
					</div>
				</div>
			</Card>
		</div>
	);
}


function GhostMode() {
	const { data, update, save, busy, saved, error } = useSettings('/settings/hardening');
	if (!data) return <PageState error={error} />;
	const s = data.settings;

	const TOGGLES = [
		{ key: 'hide_generator', label: __('Hide the WordPress version', 'ai-rank-suite'), hint: __('Removes the generator meta tag — attackers match versions to known exploits', 'ai-rank-suite') },
		{ key: 'strip_ver', label: __('Strip ?ver= from assets', 'ai-rank-suite'), hint: __('Plugin and theme versions leak through asset URLs', 'ai-rank-suite') },
		{ key: 'remove_headers', label: __('Remove RSD, wlwmanifest & shortlink tags', 'ai-rank-suite'), hint: __('Legacy discovery endpoints nothing modern needs', 'ai-rank-suite') },
		{ key: 'disable_xmlrpc', label: __('Disable XML-RPC', 'ai-rank-suite'), hint: __('A common brute-force and pingback-DDoS door. Jetpack and the mobile app need it — leave off in that case', 'ai-rank-suite') },
		{ key: 'hide_login_error', label: __('Generic login errors', 'ai-rank-suite'), hint: __('“Wrong password” confirms a username exists — replace with a neutral message', 'ai-rank-suite') },
		{ key: 'block_enum', label: __('Block user enumeration', 'ai-rank-suite'), hint: __('?author=1 redirects and the public REST users list reveal usernames for brute-forcing', 'ai-rank-suite') },
		{ key: 'security_headers', label: __('Send security headers', 'ai-rank-suite'), hint: __('X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy', 'ai-rank-suite') },
		{ key: 'hide_admin_bar', label: __('Hide the AI Rank Suite admin-bar menu', 'ai-rank-suite'), hint: __('Removes this plugin’s own entry from the WordPress toolbar. Everything stays reachable from the plugin screens', 'ai-rank-suite') },
	];

	return (
		<div className="grid gap-4">
			{error && <Notice tone="serious">{error}</Notice>}
			<Card
				title={__('Ghost Mode', 'ai-rank-suite')}
				subtitle={__('Hide WordPress fingerprints and close the doors attackers probe first — each toggle removes one signal without breaking the site', 'ai-rank-suite')}
				action={
					<div className="flex items-center gap-2">
						{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
						<Button onClick={save} busy={busy}>{__('Save', 'ai-rank-suite')}</Button>
					</div>
				}
			>
				<div className="grid gap-4">
					<div
						className="flex items-center justify-between gap-3 ars-r-lg px-4 py-3"
						style={{ background: s.enabled ? 'var(--ars-good-tonal)' : 'var(--ars-surface-2)' }}
					>
						<div>
							<div className="font-semibold text-[13.5px]">{__('Enable Ghost Mode', 'ai-rank-suite')}</div>
							<div className="text-[12px]" style={{ color: 'var(--ars-ink-2)' }}>{__('Master switch — the toggles below only apply while this is on.', 'ai-rank-suite')}</div>
						</div>
						<Switch checked={!!s.enabled} onChange={(v) => update({ enabled: v })} />
					</div>

					<div className="grid gap-3" style={{ opacity: s.enabled ? 1 : 0.5 }}>
						{TOGGLES.map((t) => (
							<div key={t.key} className="flex items-start justify-between gap-4">
								<div>
									<div className="font-medium">{t.label}</div>
									<div className="text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>
										{t.hint}
									</div>
								</div>
								<Switch checked={!!s[t.key]} onChange={(v) => update({ [t.key]: v })} disabled={!s.enabled} />
							</div>
						))}
					</div>
					<p className="m-0 text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Changes take effect on the next page load. Nothing here touches your content or SEO output.', 'ai-rank-suite')}</p>
				</div>
			</Card>
		</div>
	);
}

export default function Advanced({ tab = 'robots', onTab }) {

	const views = { robots: Robots, htaccess: Htaccess, breadcrumbs: Breadcrumbs, images: Images, ghost: GhostMode };
	const View = views[tab];

	return (
		<div className="ars-page">
			<Tabs
				tabs={[
					{ id: 'robots', label: __('Robots', 'ai-rank-suite') },
					{ id: 'htaccess', label: '.htaccess' },
					{ id: 'breadcrumbs', label: __('Breadcrumbs', 'ai-rank-suite') },
					{ id: 'images', label: __('Images', 'ai-rank-suite') },
				{ id: 'ghost', label: __('Ghost Mode', 'ai-rank-suite') },
				]}
				active={tab}
				onChange={onTab}
			/>
			<View />
		</div>
	);
}
