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

/**
 * "Let AI do" — every job the AI in this plugin can take off your hands, as a
 * to-do list with a button on each row.
 *
 * The board comes from `/ai/capabilities`, which lists only what is backed by
 * a real endpoint today and attaches a live count of open work to each row.
 * A row's count going to zero after its button was pressed is the proof that
 * the AI did what it said. Nothing here is a brochure item.
 *
 * Bulk rows drive the same server-side queue the Full Website Analyzer uses,
 * so a ten-thousand-page site finishes without a cron job or a long request.
 */

const GROUPS = [
	{ id: 'write', label: __('Write', 'ai-rank-suite'), sub: __('Copy the AI produces and saves into pages', 'ai-rank-suite') },
	{ id: 'find', label: __('Find', 'ai-rank-suite'), sub: __('What to target — proposed, never applied without you', 'ai-rank-suite') },
	{ id: 'check', label: __('Check', 'ai-rank-suite'), sub: __('Measurement the rest of the plugin reads', 'ai-rank-suite') },
	{ id: 'run', label: __('Run', 'ai-rank-suite'), sub: __('The unattended mode', 'ai-rank-suite') },
];

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

export default function LetAiDo({ compact = false }) {
	const [board, setBoard] = useState(null);
	const [error, setError] = useState(null);
	const [status, setStatus] = useState(null);
	const [running, setRunning] = useState('');
	// True once a run was started from this card, so a finished job from an
	// earlier session does not paint a stale "Finished" bar on every load.
	const [startedHere, setStartedHere] = useState(false);
	const pumping = useRef(false);
	const alive = useRef(true);

	const load = useCallback(() => api.get('/ai/capabilities').then(setBoard).catch((e) => setError(e.message)), []);

	useEffect(() => {
		load();
		api.get('/bulk/status').then(setStatus).catch(() => {});
		return () => {
			alive.current = false;
		};
	}, [load]);

	const pump = useCallback(async () => {
		if (pumping.current) return;
		pumping.current = true;
		try {
			let s = await api.post('/bulk/tick');
			setStatus(s);
			while (s.state === 'running' && alive.current) {
				s = await api.post('/bulk/tick');
				setStatus(s);
			}
			await load();
		} catch (e) {
			setError(e.message);
		} finally {
			pumping.current = false;
			setRunning('');
		}
	}, [load]);

	const act = async (row) => {
		const a = row.action || {};
		setError(null);
		if (a.kind === 'go') {
			go(a.href);
			return;
		}
		if (a.kind === 'autopilot') {
			// The autopilot has its own planner and undo; hand over to it with
			// the task preselected rather than reimplementing that here.
			go('/autopilot?tasks=' + encodeURIComponent((a.tasks || []).join(',')));
			return;
		}
		if (a.kind === 'bulk') {
			setRunning(row.id);
			setStartedHere(true);
			try {
				setStatus(await api.post('/bulk/start', { action: a.action, scope: a.scope || 'missing' }));
				pump();
			} catch (e) {
				setError(e.message);
				setRunning('');
			}
		}
	};

	const cancel = async () => {
		try {
			setStatus(await api.post('/bulk/cancel', {}));
		} catch (e) {
			setError(e.message);
		}
	};

	if (!board) {
		return (
			<Card title={__('Let AI do', 'ai-rank-suite')} icon={<IconSparkle size={18} />}>
				{error ? <Notice tone="serious">{error}</Notice> : <span className="t-caption">{__('Loading…', 'ai-rank-suite')}</span>}
			</Card>
		);
	}

	const isRunning = status?.state === 'running';
	const progress = status ? (status.progress ?? 0) : 0;
	const rows = board.rows || [];
	const totalOpen = rows.reduce((n, r) => n + (typeof r.open === 'number' && !r.free && r.id !== 'autopilot' ? r.open : 0), 0);

	return (
		/*
		 * This is the headline feature of the plugin, so it stops looking like
		 * the ninth card on the page.
		 *
		 * A tinted, ruled panel with the count as a number rather than a badge:
		 * on a real site "4,226 items waiting" is the most actionable figure
		 * anywhere in the admin, and it was set in eleven-pixel grey.
		 */
		<Card
			className={`ars-letai-card${board.connected ? ' is-live' : ''}`}
			title={
				<span className="ars-letai-title">
					{__('Let AI do', 'ai-rank-suite')}
					{board.connected && totalOpen > 0 && (
						<span className="ars-letai-count">{totalOpen.toLocaleString()}</span>
					)}
				</span>
			}
			subtitle={
				board.connected
					? `${__('Connected to', 'ai-rank-suite')} ${board.provider}. ${
							totalOpen > 0
								? `${totalOpen.toLocaleString()} ${__('items are waiting — each one is a single press.', 'ai-rank-suite')}`
								: __('Nothing is waiting. Everything below is one press away when it is.', 'ai-rank-suite')
					  }`
					: __('Everything the AI in this plugin can take off your hands — once an engine is connected.', 'ai-rank-suite')
			}
			icon={<span className="ars-letai-icon"><IconSparkle size={19} /></span>}
			action={
				board.connected ? (
					<Badge tone={totalOpen > 0 ? 'warning' : 'good'}>
						{totalOpen > 0 ? __('ready to run', 'ai-rank-suite') : __('nothing waiting', 'ai-rank-suite')}
					</Badge>
				) : (
					<Button onClick={() => go('/ai')}>{__('Connect an engine', 'ai-rank-suite')}</Button>
				)
			}
		>
			{error && <Notice tone="serious">{error}</Notice>}

			{(isRunning || (startedHere && status?.state === 'done')) && (
				<div className="grid gap-1.5 mb-4">
					<div className="flex justify-between text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
						<span>
							{isRunning ? __('Working…', 'ai-rank-suite') : __('Finished', 'ai-rank-suite')}{' '}
							{(status.done || 0).toLocaleString()} {__('of', 'ai-rank-suite')} {(status.total || 0).toLocaleString()}
							{status.failed ? ` · ${status.failed} ${__('failed', 'ai-rank-suite')}` : ''}
						</span>
						<span className="flex items-center gap-3">
							<span className="tabular-nums">{progress}%</span>
							{isRunning && (
								<button type="button" className="ars-linkbtn" onClick={cancel}>
									{__('Stop', 'ai-rank-suite')}
								</button>
							)}
						</span>
					</div>
					<Bar value={progress} />
				</div>
			)}

			<div className={`ars-letai${compact ? ' is-compact' : ''}`}>
				{GROUPS.map((g) => {
					const inGroup = rows.filter((r) => r.group === g.id && (!compact || (typeof r.open === 'number' && r.open > 0)));
					if (inGroup.length === 0) return null;
					return (
						<section key={g.id} className="ars-letai-group">
							<header className="ars-letai-head">
								<span className="t-overline">{g.label}</span>
								{!compact && <span className="t-caption">{g.sub}</span>}
							</header>
							{inGroup.map((row) => {
								const busy = running === row.id || (isRunning && row.action?.kind === 'bulk' && status?.action === row.action.action);
								const disabled = !board.connected && !row.free;
								const hasOpen = typeof row.open === 'number' && row.open > 0;
								return (
									<div key={row.id} className={`ars-letai-row${disabled ? ' is-disabled' : ''}`}>
										<div className="min-w-0 grid gap-0.5">
											<div className="flex items-center gap-2 flex-wrap">
												<span className="font-semibold text-[13px]">{row.label}</span>
												{row.free && <Badge tone="good">{__('free', 'ai-rank-suite')}</Badge>}
												{row.per_page && <Badge tone="neutral">{__('also per page', 'ai-rank-suite')}</Badge>}
											</div>
											{!compact && (
												<span className="text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
													{row.detail}
												</span>
											)}
											{!compact && <code className="ars-letai-route">{row.route}</code>}
										</div>
										<div className="ars-letai-cell">
											{hasOpen ? (
												<span className="ars-letai-open">
													<strong className="tabular-nums">{row.open.toLocaleString()}</strong>
													<span>{row.unit}</span>
												</span>
											) : typeof row.open === 'number' ? (
												<span className="ars-letai-open is-clear">✓ {__('nothing open', 'ai-rank-suite')}</span>
											) : null}
											<Button
												variant={hasOpen && !disabled ? 'primary' : 'ghost'}
												busy={busy}
												disabled={disabled || (isRunning && !busy)}
												onClick={() => act(row)}
											>
												{row.action?.kind === 'go'
													? __('Open', 'ai-rank-suite')
													: row.action?.kind === 'autopilot'
														? __('Plan run', 'ai-rank-suite')
														: hasOpen
															? __('Do it', 'ai-rank-suite')
															: __('Run again', 'ai-rank-suite')}
											</Button>
										</div>
									</div>
								);
							})}
						</section>
					);
				})}
			</div>
		</Card>
	);
}
