import React, { useEffect, useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import FirstRun from '../components/FirstRun';
import ScreenVerdict from '../components/ScreenVerdict';
import { Card, Button, Badge, Notice, PageState } from '../components/ui';
import { IconExternal, IconRefresh } from '../components/icons';

export default function Links() {
	const [data, setData] = useState(null);
	const [page, setPage] = useState(1);
	const [busy, setBusy] = useState(false);
	const [acting, setActing] = useState(null);
	const [error, setError] = useState(null);

	useEffect(() => {
		api.get(`/links?page=${page}&per_page=50`).then(setData).catch((e) => setError(e.message));
	}, [page]);

	const build = async () => {
		setBusy(true);
		setError(null);
		try {
			setData(await api.post('/links/build'));
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const act = async (id, what) => {
		setActing(id);
		setError(null);
		try {
			setData(await api.post(`/links/${id}/${what}`));
		} catch (e) {
			setError(e.message);
		} finally {
			setActing(null);
		}
	};

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

	const items = data.items || [];
	return (
		<div className="ars-page">
			{!data.built_at ? (
				<FirstRun
					badge={__('Not analysed yet', 'ai-rank-suite')}
					ringLabel={__('Internal links', 'ai-rank-suite')}
					title={__('No internal-link suggestions exist yet.', 'ai-rank-suite')}
					why={__('The analyser reads every published page, measures how similar their topics are, and proposes links between pages that talk about the same thing but do not yet point at each other — computed on your own server, no AI cost, nothing leaves the site.', 'ai-rank-suite')}
					action={busy ? __('Analysing…', 'ai-rank-suite') : __('Analyse the site', 'ai-rank-suite')}
					onAction={build}
					busy={busy}
					stats={[{ label: __('Suggestions', 'ai-rank-suite') }, { label: __('Pages analysed', 'ai-rank-suite') }, { label: __('Applied', 'ai-rank-suite') }, { label: __('Dismissed', 'ai-rank-suite') }]}
					previews={[
						{ title: __('One click to apply', 'ai-rank-suite'), text: __('Each suggestion names the source, the target and the anchor; Apply writes the link into the page and can be undone.', 'ai-rank-suite') },
						{ title: __('Targets that need links', 'ai-rank-suite'), text: __('The pages fewest others point at — the ones a suggestion helps most.', 'ai-rank-suite') },
						{ title: __('Re-run after publishing', 'ai-rank-suite'), text: __('New pages get suggestions the next time the analyser runs.', 'ai-rank-suite') },
					]}
				/>
			) : (
				<ScreenVerdict
					tone={items.length > 0 ? 'warning' : 'good'}
					text={items.length > 0 ? sprintf(_n('%d internal-link suggestion is waiting.', '%d internal-link suggestions are waiting.', items.length, 'ai-rank-suite'), items.length) : __('Every suggestion has been applied or dismissed.', 'ai-rank-suite')}
					why={items.length > 0 ? __('Each one is a page that talks about the same thing as another and does not point at it yet. Apply writes the link and can be undone.', 'ai-rank-suite') : __('Rebuild after a publishing sprint to find new pairs.', 'ai-rank-suite')}
				/>
			)}
			<Card
				title={__('Internal link suggestions', 'ai-rank-suite')}
				subtitle={__('Topic-similarity matches computed on your own server — no AI cost, no data leaves the site', 'ai-rank-suite')}
				action={
					<Button onClick={build} busy={busy}>
						<IconRefresh size={13} /> {data.built_at ? __('Rebuild', 'ai-rank-suite') : __('Analyze site', 'ai-rank-suite')}
					</Button>
				}
			>
				{error && <Notice tone="serious">{error}</Notice>}
				{data.stats && (
					<p className="m-0 mb-3 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
						{sprintf(__('Analyzed %1$s pages · %2$s new suggestions.', 'ai-rank-suite'), data.stats.analyzed, data.stats.created)}
					</p>
				)}
				{/* What the suggestions are for: the pages the graph most wants
				    strengthened. Individual link opportunities are the task list;
				    this is the reason for it. */}
				{(data.targets || []).length > 0 && (
					<div className="mb-4">
						<div className="t-overline mb-1.5">{__('Pages these links would strengthen', 'ai-rank-suite')}</div>
						<div className="grid gap-1.5">
							{data.targets.map((t) => (
								<div
									key={t.id}
									className="flex items-center justify-between gap-3 ars-r-sm px-3 py-2"
									style={{ background: 'var(--ars-surface-2)' }}
								>
									<a href={t.url} target="_blank" rel="noreferrer" className="font-medium text-[12.5px] truncate">
										{t.title}
									</a>
									<span className="t-caption shrink-0 tabular-nums">
										{sprintf(_n('%d suggestion', '%d suggestions', t.count, 'ai-rank-suite'), t.count)} · {sprintf(__('avg %s', 'ai-rank-suite'), t.avg_score)}
									</span>
								</div>
							))}
						</div>
					</div>
				)}

				{data.items.length === 0 ? (
					<p className="m-0 text-[13px]" style={{ color: 'var(--ars-ink-2)' }}>
						{data.built_at
							? __('No open suggestions — your pages are already well connected.', 'ai-rank-suite')
							: __('Run the analysis to find where your pages should link to each other.', 'ai-rank-suite')}
					</p>
				) : (
					<div className="grid gap-2">
						{data.items.map((it) => (
							<div key={it.id} className="ars-r-md p-3" style={{ background: 'var(--ars-surface-2)' }}>
								<div className="flex items-start justify-between gap-3 flex-wrap">
									<div className="min-w-0">
										<div className="text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>{__('From', 'ai-rank-suite')}{' '}<strong style={{ color: 'var(--ars-ink)' }}>{it.source}</strong> → {__('to', 'ai-rank-suite')}{' '}
											<a href={it.target_url} target="_blank" rel="noreferrer">
												{it.target} <IconExternal size={10} />
											</a>
										</div>
										<div className="mt-1.5 text-[13px]">
											{__('Link the words', 'ai-rank-suite')}{' '}
											<span
												className="font-semibold px-1.5 py-0.5 rounded"
												style={{ background: 'color-mix(in srgb, var(--ars-brand) 14%, white)', color: 'var(--ars-brand-ink)' }}
											>
												{it.anchor}
											</span>
										</div>
										{it.context && (
											<div className="mt-1 text-[12px] italic" style={{ color: 'var(--ars-ink-3)' }}>
												…{it.context}…
											</div>
										)}
									</div>
									<div className="flex items-center gap-2 shrink-0">
										<Badge tone="neutral">{sprintf(__('%d%% match', 'ai-rank-suite'), Math.round(it.score * 100))}</Badge>
										<Button busy={acting === it.id} onClick={() => act(it.id, 'apply')}>{__('Insert link', 'ai-rank-suite')}</Button>
										<Button variant="ghost" busy={acting === it.id} onClick={() => act(it.id, 'dismiss')}>{__('Dismiss', 'ai-rank-suite')}</Button>
									</div>
								</div>
							</div>
						))}
					</div>
				)}

				{/* Server-paged: at ten thousand suggestions the browser still
				    holds fifty. */}
				{data.pagination && data.pagination.total_pages > 1 && (
					<div className="flex items-center justify-between gap-3 mt-3 pt-3" style={{ borderTop: '1px solid var(--ars-line-soft)' }}>
						<span className="t-caption tabular-nums">
							{sprintf(__('%1$s suggestions · page %2$s of %3$s', 'ai-rank-suite'), data.pagination.total_items.toLocaleString(), data.pagination.page, data.pagination.total_pages)}
						</span>
						<div className="flex gap-2">
							<Button variant="ghost" disabled={page <= 1} onClick={() => setPage(page - 1)}>{__('Previous', 'ai-rank-suite')}</Button>
							<Button
								variant="ghost"
								disabled={page >= data.pagination.total_pages}
								onClick={() => setPage(page + 1)}
							>{__('Next', 'ai-rank-suite')}</Button>
						</div>
					</div>
				)}
			</Card>

			{/* Orphans: pages nothing links to. The endpoint has always returned
			    them and the screen never showed them — an orphan is the single
			    most fixable reason a page is neither crawled nor cited. */}
			{(data.orphans || []).length > 0 && (
				<Card
					title={__('Pages nothing links to', 'ai-rank-suite')}
					subtitle={__('Orphans are crawled last and cited least — one internal link is usually the whole fix', 'ai-rank-suite')}
					action={
						data.orphans_total > data.orphans.length ? (
							<Badge tone="warning">{sprintf(__('%d in total', 'ai-rank-suite'), data.orphans_total)}</Badge>
						) : null
					}
				>
					<div className="grid gap-1.5">
						{data.orphans.map((o) => (
							<div
								key={o.id}
								className="flex items-center justify-between gap-3 ars-r-sm px-3 py-2"
								style={{ background: 'var(--ars-surface-2)' }}
							>
								<a href={o.url} target="_blank" rel="noreferrer" className="font-medium text-[12.5px] truncate">
									{o.title}
								</a>
								<Button
									variant="ghost"
									onClick={() => {
										window.location.hash = `/content/${o.id}`;
									}}
								>{__('Open', 'ai-rank-suite')}</Button>
							</div>
						))}
					</div>
				</Card>
			)}
		</div>
	);
}
