import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Notice, KpiTile, LineChart, ChipBar, Advisor, Badge } from '../components/ui';

/**
 * Measure, on one screen.
 *
 * Search Console and Analytics are two Google products behind one sign-in,
 * and the plugin showed them on two screens with two period pickers and two
 * "not connected" states. What a site owner asks is one question: is the
 * site getting found, and are the people who find it staying. So this puts
 * the search numbers and the visit numbers side by side for the same days,
 * each against the same days before, and leaves the detail to the two
 * screens behind it.
 */
const PERIODS = [
	{ id: '7', label: '7' },
	{ id: '28', label: '28' },
	{ id: '90', label: '90' },
];

const num = (n) => Number(n || 0).toLocaleString();
const pct = (n, d) => (d > 0 ? Math.round(((n - d) / d) * 100) : null);

export default function Measure() {
	const [days, setDays] = useState('28');
	const [status, setStatus] = useState(null);
	const [gsc, setGsc] = useState(null);
	const [ga, setGa] = useState(null);
	const [bing, setBing] = useState(null);
	const [error, setError] = useState(null);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		api.get('/gsc/status').then(setStatus).catch((e) => setError(e.message));
		api.get('/bing').then(setBing).catch(() => setBing(null));
	}, []);

	useEffect(() => {
		if (!status?.connected) return;
		setLoading(true);
		Promise.allSettled([api.get(`/gsc/performance?days=${days}`), api.get(`/analytics/report?days=${days}`)]).then(([g, a]) => {
			setGsc(g.status === 'fulfilled' ? g.value : { error: g.reason?.message });
			setGa(a.status === 'fulfilled' ? a.value : { error: a.reason?.message });
			setLoading(false);
		});
	}, [status?.connected, days]);

	const go = (hash) => {
		window.location.hash = hash;
	};

	if (error) return <Notice tone="serious">{error}</Notice>;
	if (!status) return <Card>{__('Reading the connections…', 'ai-rank-suite')}</Card>;

	if (!status.connected) {
		return (
			<div className="ars-page">
				<Advisor
					tone="neutral"
					text={__('Search Console and Analytics are not connected yet.', 'ai-rank-suite')}
					sub={__('One sign-in with Google connects both, read-only. This screen then shows clicks, impressions, users and sessions for the same days side by side.', 'ai-rank-suite')}
					action={__('Connect Google', 'ai-rank-suite')}
					onAction={() => go('/search-console')}
				/>
				<Card title={__('What this screen will show', 'ai-rank-suite')}>
					<ul className="m-0 pl-5 text-[13px] grid gap-1">
						<li>{__('Search: clicks, impressions, click-through rate and average position, against the same number of days before.', 'ai-rank-suite')}</li>
						<li>{__('Visits: users, sessions, page views and engagement from Google Analytics 4, for the same period.', 'ai-rank-suite')}</li>
						<li>{__('The two lines on one time axis, and the top pages with both numbers next to each other.', 'ai-rank-suite')}</li>
						<li>{__('Bing beside Google, once its API key is stored.', 'ai-rank-suite')}</li>
					</ul>
				</Card>
			</div>
		);
	}

	const t = gsc?.totals || {};
	const p = gsc?.previous || {};
	const g = ga?.totals || {};
	const tone = (delta, invert = false) => (delta === null || delta === undefined ? 'plain' : (invert ? -delta : delta) >= 0 ? 'green' : 'red');
	const delta = (now, before) => {
		const d = pct(Number(now || 0), Number(before || 0));
		return d === null ? undefined : d;
	};

	// Top pages from both sources on one table, joined on the path.
	const gaPages = new Map((ga?.pages || []).map((r) => [String(r.path || r.page || '').replace(/\/$/, ''), r]));
	const joined = (gsc?.pages || []).slice(0, 10).map((r) => {
		let path = '';
		try {
			path = new URL(r.page || r.key || r.url || '', window.location.origin).pathname.replace(/\/$/, '');
		} catch (e) {
			path = String(r.page || '').replace(/\/$/, '');
		}
		const a = gaPages.get(path) || gaPages.get(path + '/') || null;
		return { path: path || '/', clicks: r.clicks, impressions: r.impressions, position: r.position, users: a ? a.users : null, views: a ? a.views ?? a.pageviews : null };
	});

	return (
		<div className="ars-page">
			<Advisor
				tone="good"
				text={sprintf(__('Connected to %s.', 'ai-rank-suite'), status.property || __('your Search Console property', 'ai-rank-suite'))}
				sub={__('Search and visits for the same days, each against the same number of days immediately before. Detail and settings sit behind Search Console and Analytics.', 'ai-rank-suite')}
				action={__('Search Console', 'ai-rank-suite')}
				onAction={() => go('/search-console')}
			/>

			<div className="flex items-center justify-between gap-3 flex-wrap">
				<ChipBar options={PERIODS.map((o) => ({ id: o.id, label: sprintf(__('%s days', 'ai-rank-suite'), o.label) }))} value={days} onChange={setDays} label={__('Period', 'ai-rank-suite')} />
				{loading && <Badge tone="neutral">{__('Reading…', 'ai-rank-suite')}</Badge>}
			</div>

			<Card title={__('Search', 'ai-rank-suite')} subtitle={__('Google Search Console. Position is an average; lower is better.', 'ai-rank-suite')} action={<Button variant="ghost" onClick={() => go('/search-console')}>{__('Queries and pages', 'ai-rank-suite')}</Button>}>
				{gsc?.error ? (
					<Notice tone="warning">{gsc.error}</Notice>
				) : (
					<div className="ars-metrics" data-columns="4" style={{ '--ars-metrics-cols': 4 }}>
						<KpiTile label={__('Clicks', 'ai-rank-suite')} value={num(t.clicks)} delta={delta(t.clicks, p.clicks)} tone={tone(delta(t.clicks, p.clicks))} />
						<KpiTile label={__('Impressions', 'ai-rank-suite')} value={num(t.impressions)} delta={delta(t.impressions, p.impressions)} tone={tone(delta(t.impressions, p.impressions))} />
						<KpiTile label={__('Click-through rate', 'ai-rank-suite')} value={`${Number(t.ctr || 0).toFixed(1)}%`} />
						<KpiTile label={__('Average position', 'ai-rank-suite')} value={Number(t.position || 0).toFixed(1)} delta={p.position ? Math.round((Number(t.position) - Number(p.position)) * 10) / 10 : undefined} tone={p.position ? (Number(t.position) <= Number(p.position) ? 'green' : 'red') : 'plain'} />
					</div>
				)}
				{gsc?.series?.length > 2 && (
					<div className="mt-3">
						<LineChart data={gsc.series.map((s) => ({ date: s.date, value: s.clicks }))} label={__('Clicks', 'ai-rank-suite')} color="var(--ars-brand)" height={120} formatValue={(v) => num(v)} bleed />
					</div>
				)}
			</Card>

			<Card title={__('Visits', 'ai-rank-suite')} subtitle={__('Google Analytics 4, the same period.', 'ai-rank-suite')} action={<Button variant="ghost" onClick={() => go('/analytics')}>{__('Analytics', 'ai-rank-suite')}</Button>}>
				{ga?.error ? (
					<Notice tone="warning">{ga.error}</Notice>
				) : ga && !ga.totals ? (
					<Notice tone="neutral">{__('Analytics is not set up for this site yet. Pick the GA4 property under Analytics; the same Google sign-in covers it.', 'ai-rank-suite')}</Notice>
				) : (
					<div className="ars-metrics" data-columns="4" style={{ '--ars-metrics-cols': 4 }}>
						<KpiTile label={__('Users', 'ai-rank-suite')} value={num(g.users)} />
						<KpiTile label={__('Sessions', 'ai-rank-suite')} value={num(g.sessions)} />
						<KpiTile label={__('Page views', 'ai-rank-suite')} value={num(g.pageviews)} />
						<KpiTile label={__('Engagement', 'ai-rank-suite')} value={`${Number(g.engagement || 0).toFixed(1)}%`} />
					</div>
				)}
				{ga?.series?.length > 2 && (
					<div className="mt-3">
						<LineChart data={ga.series} label={__('Users', 'ai-rank-suite')} color="var(--ars-good)" height={120} formatValue={(v) => num(v)} bleed />
					</div>
				)}
			</Card>

			{joined.length > 0 && (
				<Card title={__('Top pages, both numbers', 'ai-rank-suite')} subtitle={__('The pages Google shows most, with what Analytics saw on them in the same days.', 'ai-rank-suite')} flush>
					<table className="ars-table">
						<thead>
							<tr>
								<th>{__('Page', 'ai-rank-suite')}</th>
								<th className="text-right">{__('Clicks', 'ai-rank-suite')}</th>
								<th className="text-right">{__('Impressions', 'ai-rank-suite')}</th>
								<th className="text-right">{__('Position', 'ai-rank-suite')}</th>
								<th className="text-right">{__('Users', 'ai-rank-suite')}</th>
							</tr>
						</thead>
						<tbody>
							{joined.map((r) => (
								<tr key={r.path}>
									<td className="ars-mono text-[12px]">{r.path}</td>
									<td className="text-right tabular-nums">{num(r.clicks)}</td>
									<td className="text-right tabular-nums">{num(r.impressions)}</td>
									<td className="text-right tabular-nums">{Number(r.position || 0).toFixed(1)}</td>
									<td className="text-right tabular-nums">{r.users === null ? '–' : num(r.users)}</td>
								</tr>
							))}
						</tbody>
					</table>
				</Card>
			)}

			<Card title={__('Bing', 'ai-rank-suite')} subtitle={bing?.has_key ? __('Connected. Clicks and index coverage on Bing sit behind Search Console → Bing.', 'ai-rank-suite') : __('Not connected. Bing is the index Copilot answers from; its numbers appear here once the API key is stored.', 'ai-rank-suite')} action={<Button variant="ghost" onClick={() => go('/search-console/bing')}>{__('Bing', 'ai-rank-suite')}</Button>} />
		</div>
	);
}
