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

/**
 * The review queue for suggest/approve autopilot runs.
 *
 * Every parked proposal, newest first, with the current value beside it and
 * an editable copy of the proposal. Apply writes what is in the box; Reject
 * discards. Paged on the server; a ten-thousand-page run does not land in
 * the browser at once.
 */
export default function ProposalQueue({ refreshKey }) {
	const [data, setData] = useState(null);
	const [page, setPage] = useState(1);
	const [drafts, setDrafts] = useState({});
	const [busy, setBusy] = useState('');
	const [error, setError] = useState(null);

	const load = () =>
		api
			.get(`/autopilot/proposals?page=${page}&per_page=25`)
			.then((r) => {
				setData(r);
				setDrafts(Object.fromEntries(r.items.map((it) => [`${it.post_id}:${it.task}`, it.task === 'faq' ? JSON.stringify(it.proposal, null, 1) : it.proposal])));
			})
			.catch((e) => setError(e.message));

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

	if (!data) return null;
	if (data.total === 0) return null;

	const act = async (it, kind) => {
		const key = `${it.post_id}:${it.task}`;
		setBusy(key + kind);
		setError(null);
		try {
			if (kind === 'apply') {
				let value = drafts[key];
				if (it.task === 'faq') {
					try {
						value = JSON.parse(value);
					} catch (e) {
						throw new Error(__('The FAQ list is not valid JSON — fix it or reject.', 'ai-rank-suite'));
					}
				}
				await api.post('/autopilot/proposals/apply', { post_id: it.post_id, task: it.task, value });
			} else {
				await api.post('/autopilot/proposals/reject', { post_id: it.post_id, task: it.task });
			}
			await load();
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy('');
		}
	};

	const pages = Math.max(1, Math.ceil(data.total / 25));

	return (
		<Card
			title={__('Proposals waiting for review', 'ai-rank-suite')}
			subtitle={__('What the last suggest/approve runs parked. Nothing here is live until you apply it — as proposed, or edited.', 'ai-rank-suite')}
			action={<Badge tone="warning">{data.total.toLocaleString()} {__('open', 'ai-rank-suite')}</Badge>}
		>
			{error && <Notice tone="serious">{error}</Notice>}
			<div className="grid gap-2">
				{data.items.map((it) => {
					const key = `${it.post_id}:${it.task}`;
					return (
						<div key={key} className="ars-review-field">
							<div className="flex items-center justify-between gap-2 flex-wrap">
								<span className="flex items-center gap-2 flex-wrap">
									<Badge tone="brand">{it.task}</Badge>
									<a href={`#/content/${it.post_id}`} className="font-semibold text-[13px]">
										{it.title || `#${it.post_id}`}
									</a>
								</span>
								<span className="flex items-center gap-2">
									<Button variant="ghost" busy={busy === key + 'reject'} onClick={() => act(it, 'reject')}>
										{__('Reject', 'ai-rank-suite')}
									</Button>
									<Button busy={busy === key + 'apply'} onClick={() => act(it, 'apply')}>
										{__('Apply', 'ai-rank-suite')}
									</Button>
								</span>
							</div>
							<div className="ars-review-orig">
								<span className="t-caption">{__('Now', 'ai-rank-suite')}:</span>{' '}
								{it.task === 'faq'
									? `${Array.isArray(it.current) ? it.current.length : 0} ${__('FAQ items', 'ai-rank-suite')}`
									: it.current || <em style={{ color: 'var(--ars-ink-3)' }}>{__('empty', 'ai-rank-suite')}</em>}
							</div>
							<textarea rows={it.task === 'faq' ? 6 : 2} value={drafts[key] || ''} onChange={(e) => setDrafts({ ...drafts, [key]: e.target.value })} />
						</div>
					);
				})}
			</div>
			{pages > 1 && (
				<div className="flex items-center justify-between gap-3 mt-3">
					<span className="t-caption">
						{__('Page', 'ai-rank-suite')} {page} {__('of', 'ai-rank-suite')} {pages}
					</span>
					<div className="flex items-center gap-1">
						<Button variant="ghost" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
							‹
						</Button>
						<Button variant="ghost" disabled={page >= pages} onClick={() => setPage((p) => p + 1)}>
							›
						</Button>
					</div>
				</div>
			)}
		</Card>
	);
}
