import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Badge, Notice, Field, Switch, MetricGrid, Sparkline, RankBar, SegmentBar } from './ui';
import Explain from './Explain';
import { IconChart, IconRefresh, IconSparkle, IconExternal } from './icons';

/**
 * Matomo.
 *
 * Two reasons it is here, and the second is the interesting one. Plenty of
 * sites cannot use Google Analytics at all, so a paid SEO plugin that only
 * speaks GA4 is unusable for them. And the only hard evidence that any of this
 * work is paying off is a visit whose referrer is an AI assistant — Matomo
 * returns the full referrer list unsampled and without a processing delay, so
 * that question has an exact answer here rather than an estimate.
 */
export default function MatomoPanel({ settings, onSave, saving }) {
	const [data, setData] = useState(null);
	const [error, setError] = useState(null);
	const [busy, setBusy] = useState(false);
	const [token, setToken] = useState('');
	const [verified, setVerified] = useState(null);
	const [days, setDays] = useState(30);
	const [draft, setDraft] = useState(null);

	const s = draft || settings || {};

	const load = (d = days) => {
		setBusy(true);
		setError(null);
		api
			.get(`/analytics/matomo?days=${d}`)
			.then(setData)
			.catch((e) => setError(e.message))
			.finally(() => setBusy(false));
	};

	useEffect(() => {
		load();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	const patch = (p) => setDraft({ ...s, ...p });

	const saveAll = async () => {
		setBusy(true);
		setError(null);
		try {
			// The token goes to its own endpoint because it is stored
			// encrypted and never comes back — sending it with the settings
			// would mean the settings payload carried a secret it cannot show.
			if (token) {
				await api.put('/analytics/matomo', { token });
				setToken('');
			}
			await onSave(s);
			setDraft(null);
			load();
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const verify = async () => {
		setBusy(true);
		setVerified(null);
		setError(null);
		try {
			setVerified(await api.post('/analytics/matomo/verify'));
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const ai = data?.assistants;

	return (
		<div className="grid gap-3">
			{error && <Notice tone="serious">{error}</Notice>}

			{data?.configured && ai && (
				<Card
					icon={<IconSparkle size={16} />}
					title={__('Visits from AI assistants', 'ai-rank-suite')}
					subtitle={__('Real people who arrived from an AI answer — the only hard evidence that being cited is working', 'ai-rank-suite')}
					action={
						<div className="flex items-center gap-2">
							<select
								value={days}
								onChange={(e) => {
									setDays(Number(e.target.value));
									load(Number(e.target.value));
								}}
								style={{ maxWidth: 130 }}
								aria-label={__('Period', 'ai-rank-suite')}
							>
								<option value={7}>{__('Last 7 days', 'ai-rank-suite')}</option>
								<option value={30}>{__('Last 30 days', 'ai-rank-suite')}</option>
								<option value={90}>{__('Last 90 days', 'ai-rank-suite')}</option>
								<option value={365}>{__('Last year', 'ai-rank-suite')}</option>
							</select>
							<Button variant="ghost" busy={busy} onClick={() => load()}>
								<IconRefresh size={13} />
							</Button>
						</div>
					}
				>
					<MetricGrid
						columns={4}
						metrics={[
							{
								id: 'assistants',
								label: __('From assistants', 'ai-rank-suite'),
								hint: __('Visits whose referrer names an AI assistant. A floor, not a total — many assistants strip the referrer entirely.', 'ai-rank-suite'),
								value: ai.total.toLocaleString(),
								sub: sprintf(__('%s%% of all referred visits', 'ai-rank-suite'), ai.share),
							},
							{
								id: 'other',
								label: __('From other sites', 'ai-rank-suite'),
								hint: __('Ordinary referral traffic, for scale.', 'ai-rank-suite'),
								value: ai.other.toLocaleString(),
							},
							{
								id: 'visits',
								label: __('Visits', 'ai-rank-suite'),
								hint: __('All visits in the selected period, straight from Matomo.', 'ai-rank-suite'),
								value: (data.totals?.visits || 0).toLocaleString(),
								sub: sprintf(__('%s people', 'ai-rank-suite'), (data.totals?.visitors || 0).toLocaleString()),
							},
							{
								id: 'depth',
								label: __('Pages per visit', 'ai-rank-suite'),
								value:
									data.totals?.visits > 0
										? (data.totals.actions / data.totals.visits).toFixed(1)
										: '—',
								sub: sprintf(__('%s%% bounced', 'ai-rank-suite'), data.totals?.bounce || 0),
							},
						]}
					/>

					{ai.engines.length > 0 ? (
						<div className="mt-4">
							<RankBar
								items={ai.engines.map((e) => ({ label: e.name, value: e.visits }))}
								max={Math.max(...ai.engines.map((e) => e.visits))}
								color="var(--ars-brand)"
								format={(v) => sprintf(__('%s visits', 'ai-rank-suite'), v.toLocaleString())}
							/>
						</div>
					) : (
						<Notice tone="warning">
							{__('No visits from a named AI assistant in this period. That is normal early on — being cited takes weeks to turn into clicks, and many assistants strip the referrer entirely, so this number is a floor rather than a total.', 'ai-rank-suite')}
						</Notice>
					)}

					{data.series?.length > 1 && (
						<div className="mt-4">
							<div className="t-overline mb-1">{__('Visits per day', 'ai-rank-suite')}</div>
							<Sparkline data={data.series.map((d) => d.value)} height={44} color="var(--ars-brand)" />
						</div>
					)}
				</Card>
			)}

			{data?.configured && (data.channels || []).length > 0 && (
				<div className="grid gap-3 lg:grid-cols-2">
					<Card title={__('Where visits come from', 'ai-rank-suite')} subtitle="Matomo's own channel grouping" flush>
						<div className="p-4">
							<SegmentBar
								segments={data.channels.map((c, i) => ({
									label: c.label,
									value: c.visits,
									color: ['var(--ars-series-1)', 'var(--ars-series-2)', 'var(--ars-series-3)', 'var(--ars-series-4)', 'var(--ars-ink-3)'][i % 5],
								}))}
							/>
						</div>
					</Card>
					<Card title={__('Most visited pages', 'ai-rank-suite')} flush>
						<div className="ars-table-wrap">
							<table className="ars-table">
								<thead>
									<tr>
										<th>{__('Page', 'ai-rank-suite')}</th>
										<th className="is-num is-narrow">{__('Views', 'ai-rank-suite')}</th>
									</tr>
								</thead>
								<tbody>
									{(data.pages || []).slice(0, 10).map((p, i) => (
										<tr key={i}>
											<td className="truncate">{p.path}</td>
											<td className="is-num is-narrow tabular-nums">{p.views.toLocaleString()}</td>
										</tr>
									))}
								</tbody>
							</table>
						</div>
					</Card>
				</div>
			)}

			<Card
				icon={<IconChart size={16} />}
				title={__('Matomo connection', 'ai-rank-suite')}
				subtitle={__('Your own Matomo — self-hosted or Matomo Cloud. Nothing is proxied anywhere.', 'ai-rank-suite')}
				action={
					<div className="flex items-center gap-2">
						{data?.configured && <Badge tone="good">{__('Connected', 'ai-rank-suite')}</Badge>}
						<Button busy={busy || saving} onClick={saveAll} disabled={!draft && !token}>{__('Save', 'ai-rank-suite')}</Button>
					</div>
				}
			>
				<div className="grid gap-3 sm:grid-cols-2">
					<Field
						label={__('Matomo URL', 'ai-rank-suite')}
						hint={__('The root, e.g. https://analytics.example.com/ — not the path to index.php.', 'ai-rank-suite')}
						className="sm:col-span-2"
					>
						<input
							type="url"
							value={s.matomo_url || ''}
							placeholder="https://analytics.example.com/"
							onChange={(e) => patch({ matomo_url: e.target.value })}
						/>
					</Field>
					<Field label={__('Site ID', 'ai-rank-suite')} hint={__('The idSite number in Matomo, usually 1.', 'ai-rank-suite')}>
						<input
							type="number"
							min="1"
							value={s.matomo_site_id || ''}
							onChange={(e) => patch({ matomo_site_id: Number(e.target.value) })}
						/>
					</Field>
					<Field
						label={__('API token', 'ai-rank-suite')}
						hint={
							data?.hint
								? sprintf(__('Stored (%s). Enter a new one to replace it.', 'ai-rank-suite'), data.hint)
								: __('Matomo → Administration → Personal → Security → Auth tokens. Stored encrypted; sent by POST, never in a URL.', 'ai-rank-suite')
						}
					>
						<input
							type="password"
							autoComplete="off"
							value={token}
							placeholder={data?.hint ? '••••••••' : __('Paste the token', 'ai-rank-suite')}
							onChange={(e) => setToken(e.target.value)}
						/>
					</Field>
				</div>

				<div className="flex items-center gap-2 flex-wrap mt-3">
					<Button variant="ghost" busy={busy} onClick={verify}>{__('Test the connection', 'ai-rank-suite')}</Button>
					{verified && (
						<>
							<Badge tone={verified.matches ? 'good' : 'warning'}>
								{verified.name || __('Connected', 'ai-rank-suite')}
							</Badge>
							{!verified.matches && (
								<span className="text-[12px]" style={{ color: 'var(--ars-warning)' }}>
									{sprintf(__('That Matomo site is set up for %s, not this one — the report would be somebody else’s traffic.', 'ai-rank-suite'), verified.main_url || __('another address', 'ai-rank-suite'))}
								</span>
							)}
						</>
					)}
				</div>

				<div className="grid gap-2 mt-4">
					<Switch
						checked={!!s.matomo_enabled}
						onChange={(v) => patch({ matomo_enabled: v })}
						label={__('Read reports from Matomo', 'ai-rank-suite')}
					/>
					<Switch
						checked={!!s.matomo_track}
						onChange={(v) => patch({ matomo_track: v })}
						label={__('Also add the tracking code to the site', 'ai-rank-suite')}
					/>
					{s.matomo_track && (
						<div className="ml-[48px] grid gap-2">
							<Switch
								checked={!!s.matomo_cookieless}
								onChange={(v) => patch({ matomo_cookieless: v })}
								label={__('Track without cookies', 'ai-rank-suite')}
							/>
							<p className="m-0 text-[12px]" style={{ color: 'var(--ars-ink-2)' }}>
								{__('Cookieless is on by default. Matomo can measure without setting a cookie, and a site that chose Matomo over Google Analytics has usually chosen it for exactly that reason. Leave the tracking code off if Matomo is already installed by another plugin or by your theme — two snippets means every visit counted twice.', 'ai-rank-suite')}
							</p>
						</div>
					)}
				</div>
			</Card>

			<Explain title={__('Why this number is a floor, not a total', 'ai-rank-suite')}>
				<p>
					{__('A visit is attributed to an assistant only when the browser sends a referrer naming it. Several assistants strip the referrer entirely, some open links in an in-app browser that sends nothing, and anyone who reads an answer and then types your name into a search box arrives as organic search. So the real influence of AI answers is always larger than this figure — treat it as the part you can prove.', 'ai-rank-suite')}
				</p>
				<p>
					{__('The direction still matters more than the level. If this number is climbing month over month while your published pages are unchanged, the citations are working.', 'ai-rank-suite')}
				</p>
				<p className="flex items-center gap-1">
					<a href="https://matomo.org/faq/general/faq_114/" target="_blank" rel="noreferrer">{__('How to create a Matomo auth token', 'ai-rank-suite')}</a>
					<IconExternal size={10} />
				</p>
			</Explain>
		</div>
	);
}
