import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Badge, Notice } from './ui';
import { IconSparkle } from './icons';

/**
 * The site-audit copilot.
 *
 * The deterministic checks are the truth; the copilot may only group them,
 * explain the likely cause and the impact, estimate effort and risk, and put
 * them in an order worth working. Ids that do not exist in the run are
 * dropped server-side, so nothing here can invent a finding.
 */
const tone = (v) => (v === 'high' ? 'serious' : v === 'medium' ? 'warning' : 'good');

export default function AuditCopilot({ hasRun }) {
	const [data, setData] = useState(null);
	const [busy, setBusy] = useState(false);
	const [error, setError] = useState(null);

	const run = async () => {
		setBusy(true);
		setError(null);
		try {
			setData(await api.post('/ai/audit/explain', {}));
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	return (
		<Card
			title={__('Audit copilot', 'ai-rank-suite')}
			subtitle={__('Turns the findings into a plan: grouped, explained, with effort and risk, in the order worth working. The checks stay the source of truth — the AI only reads them.', 'ai-rank-suite')}
			icon={<IconSparkle size={18} />}
			action={
				<Button onClick={run} busy={busy} disabled={!hasRun}>
					<IconSparkle size={13} /> {data ? __('Explain again', 'ai-rank-suite') : __('Explain this audit', 'ai-rank-suite')}
				</Button>
			}
		>
			{!hasRun && <span className="t-caption">{__('Run the audit first; the copilot explains its results.', 'ai-rank-suite')}</span>}
			{hasRun && !data && !error && !busy && (
				<div className="ars-copilot-idle">
					<span className="ars-copilot-idle-mark" aria-hidden>
						<IconSparkle size={14} />
					</span>
					<span>
						{__('Nothing explained yet. The AI reads every finding of the last run, groups them by cause, and writes the steps in the order worth working — with effort and risk for each group.', 'ai-rank-suite')}
					</span>
				</div>
			)}
			{busy && !data && <span className="t-caption">{__('Reading the findings…', 'ai-rank-suite')}</span>}
			{error && <Notice tone="serious">{error}</Notice>}
			{data && data.groups.length === 0 && <Notice tone="good">{__('Nothing to explain — the run has no findings.', 'ai-rank-suite')}</Notice>}
			{data && data.groups.length > 0 && (
				<div className="grid gap-3">
					{data.groups.map((g, i) => {
						const rows = data.findings.filter((f) => g.finding_ids.includes(f.id));
						const pages = rows.reduce((n, f) => n + f.count, 0);
						return (
							<div key={i} className="ars-copilot-group">
								<div className="flex items-start justify-between gap-3 flex-wrap">
									<div className="flex items-center gap-2 flex-wrap">
										<span className="ars-copilot-rank">{g.priority}</span>
										<span className="font-semibold text-[13.5px]">{g.title}</span>
									</div>
									<span className="flex items-center gap-1.5 flex-wrap">
										<Badge tone={tone(g.effort)}>{__('effort', 'ai-rank-suite')} {g.effort}</Badge>
										<Badge tone={tone(g.risk)}>{__('risk', 'ai-rank-suite')} {g.risk}</Badge>
										<Badge tone="neutral">{pages.toLocaleString()} {__('pages', 'ai-rank-suite')}</Badge>
									</span>
								</div>
								{g.cause && (
									<p className="m-0 text-[12.5px]">
										<strong>{__('Cause', 'ai-rank-suite')}:</strong> {g.cause}
									</p>
								)}
								{g.impact && (
									<p className="m-0 text-[12.5px]">
										<strong>{__('Impact', 'ai-rank-suite')}:</strong> {g.impact}
									</p>
								)}
								<ol className="m-0 pl-5 grid gap-1 text-[12.5px]">
									{g.steps.map((s, k) => (
										<li key={k}>{s}</li>
									))}
								</ol>
								<div className="flex gap-1 flex-wrap">
									{rows.map((f) => (
										<Badge key={f.id} tone={f.severity === 'critical' ? 'serious' : f.severity === 'warning' ? 'warning' : 'neutral'}>
											{f.label} · {f.count}
										</Badge>
									))}
								</div>
							</div>
						);
					})}
					{data.receipt && data.receipt.model && (
						<span className="t-caption">
							{data.receipt.provider} · {data.receipt.model} · {data.receipt.cost} · {data.receipt.latency_ms} ms
						</span>
					)}
				</div>
			)}
		</Card>
	);
}
