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

const ACTIONS = [
	{
		id: 'analyze',
		label: __('Analyze all pages', 'ai-rank-suite'),
		desc: __('Recalculate GEO + SEO scores for every published page. Fast, free, no AI needed.', 'ai-rank-suite'),
		ai: false,
	},
	{
		id: 'describe',
		label: __('Write meta descriptions', 'ai-rank-suite'),
		desc: __('Generate a meta description and an AI summary per page. Uses your AI key.', 'ai-rank-suite'),
		ai: true,
	},
	{
		id: 'faq',
		label: __('Generate FAQs', 'ai-rank-suite'),
		desc: __('Create grounded Q&A per page — feeds FAQPage schema. Uses your AI key.', 'ai-rank-suite'),
		ai: true,
	},
];

export default function Bulk() {
	const [status, setStatus] = useState(null);
	const [scope, setScope] = useState('missing');
	const [error, setError] = useState(null);
	const [starting, setStarting] = useState(null);
	const running = useRef(false);

	const pump = async () => {
		if (running.current) return;
		running.current = true;
		try {
			let s = await api.post('/bulk/tick');
			setStatus(s);
			while (s.state === 'running') {
				if (s.busy || s.error) await new Promise((r) => setTimeout(r, 2000));
				s = await api.post('/bulk/tick');
				setStatus(s);
			}
		} catch (e) {
			setError(e.message);
		} finally {
			running.current = false;
		}
	};

	useEffect(() => {
		api
			.get('/bulk/status')
			.then((s) => {
				setStatus(s);
				if (s.state === 'running') pump();
			})
			.catch(() => {});
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	const start = async (action) => {
		setStarting(action);
		setError(null);
		try {
			setStatus(await api.post('/bulk/start', { action, scope }));
			pump();
		} catch (e) {
			setError(e.message);
		} finally {
			setStarting(null);
		}
	};

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

	const isRunning = status?.state === 'running';

	return (
		<div className="ars-page">
			{error && <Notice tone="serious">{error}</Notice>}

			{status && status.state !== 'idle' && (
				<Card
					/*
					 * Marked for translation, like everything beside it. These
					 * three were bare strings, so the card printed "Finished"
					 * in English above a German subtitle — and an unmarked
					 * string is not a missing translation, it is not a string
					 * the translator ever sees.
					 */
					title={isRunning
						? __('Working…', 'ai-rank-suite')
						: status.state === 'done'
							? __('Finished', 'ai-rank-suite')
							: __('Cancelled', 'ai-rank-suite')}
					subtitle={sprintf(__('%1$s of %2$s pages processed', 'ai-rank-suite'), status.done, status.total) + (status.failed ? ' · ' + sprintf(__('%d failed', 'ai-rank-suite'), status.failed) : '')}
					action={
						isRunning ? (
							<Button variant="ghost" onClick={cancel}>{__('Cancel', 'ai-rank-suite')}</Button>
						) : (
							<Badge tone={status.failed ? 'warning' : 'good'}>
								{status.failed ? sprintf(__('%d failed', 'ai-rank-suite'), status.failed) : '✓ ' + __('Complete', 'ai-rank-suite')}
							</Badge>
						)
					}
				>
					<div className="grid gap-2">
						<Progress
							label={sprintf(
								/* translators: %s: how many items are left in the run. */
								__('%s remaining', 'ai-rank-suite'),
								Number(status.remaining || 0).toLocaleString()
							)}
							total={100}
							percent={status.progress}
						/>
						{status.errors?.length > 0 && (
							<ul className="m-0 mt-1 pl-5 text-[12px]" style={{ color: 'var(--ars-serious)' }}>
								{status.errors.map((e, i) => (
									<li key={i}>{e}</li>
								))}
							</ul>
						)}
					</div>
				</Card>
			)}

			<Card
				title={__('Bulk optimization', 'ai-rank-suite')}
				subtitle={__('Apply an action across your whole site — resumable and cancellable at any time', 'ai-rank-suite')}
				action={
					<div className="inline-flex gap-1 p-1 ars-r-md" style={{ background: 'var(--ars-surface-3)' }}>
						{[
							{ id: 'missing', label: __('Only missing', 'ai-rank-suite') },
							{ id: 'all', label: __('All pages', 'ai-rank-suite') },
						].map((s) => (
							<button
								key={s.id}
								type="button"
								onClick={() => setScope(s.id)}
								className="px-3 py-1.5 ars-r-sm text-[12.5px] font-semibold border-0 cursor-pointer"
								style={
									scope === s.id
										? { background: 'var(--ars-surface)', color: 'var(--ars-ink)' }
										: { background: 'transparent', color: 'var(--ars-ink-2)' }
								}
							>
								{s.label}
							</button>
						))}
					</div>
				}
			>
				<div className="grid gap-2.5">
					{ACTIONS.map((a) => (
						<div
							key={a.id}
							className="flex items-center justify-between gap-4 ars-r-md p-3.5"
							style={{ background: 'var(--ars-surface-2)' }}
						>
							<div>
								<div className="font-semibold flex items-center gap-1.5">
									{a.ai && <IconSparkle size={13} />}
									{a.label}
								</div>
								<div className="text-[12.5px] mt-0.5" style={{ color: 'var(--ars-ink-2)' }}>
									{a.desc}
								</div>
							</div>
							<Button
								variant={a.ai ? 'primary' : 'ghost'}
								busy={starting === a.id}
								disabled={isRunning}
								onClick={() => start(a.id)}
							>
								{!a.ai && <IconRefresh size={13} />} Run
							</Button>
						</div>
					))}
				</div>
				<p className="m-0 mt-3 text-[12px]" style={{ color: 'var(--ars-ink-3)' }}>
					{__('AI actions send one small request per page to your provider. Keep this tab open while a job runs — progress is saved, so you can close it and resume later.', 'ai-rank-suite')}
				</p>
			</Card>
		</div>
	);
}
