import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Badge, Notice, Bar, Field, Switch, ColumnChart } from './ui';
import { IconChart } from './icons';

/**
 * AI usage and budget.
 *
 * Every provider call writes a ledger row (tokens, cost, latency, outcome);
 * this shows the sums and lets the owner set the ceilings the client checks
 * before every call. Costs are list prices per model, so they are estimates
 * of the vendor's invoice, not the invoice — the panel says so.
 */
const usd = (micro) => {
	const v = (micro || 0) / 1e6;
	return v > 0 && v < 0.01 ? `$${v.toFixed(4)}` : `$${v.toFixed(2)}`;
};

export default function AiBudget() {
	const [board, setBoard] = useState(null);
	const [draft, setDraft] = useState(null);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);

	useEffect(() => {
		api.get('/ai/usage').then(setBoard).catch((e) => setError(e.message));
	}, []);

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

	const stored = board.budget;
	const b = draft || stored;
	const dirty = draft !== null && JSON.stringify(draft) !== JSON.stringify(stored);
	const set = (k, v) => setDraft({ ...b, [k]: v });

	const save = async () => {
		setBusy(true);
		setError(null);
		try {
			setBoard(await api.put('/ai/usage', { budget: b }));
			setDraft(null);
			setSaved(true);
			setTimeout(() => setSaved(false), 1800);
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const todayPct = board.pct.today;
	const monthPct = board.pct.month;
	const warn = b.warn_pct || 80;
	const tone = (p) => (p >= 100 ? 'serious' : p >= warn ? 'warning' : 'good');

	return (
		<Card
			title={__('AI usage & budget', 'ai-rank-suite')}
			subtitle={__(
				'Measured from every call the plugin makes, priced at the vendor list rate per model. An estimate of your invoice, checked before each call so a runaway job stops itself.',
				'ai-rank-suite'
			)}
			icon={<IconChart size={18} />}
			action={saved ? <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge> : null}
		>
			{error && <Notice tone="serious">{error}</Notice>}

			<div className="grid gap-4 md:grid-cols-2">
				<div className="grid gap-1.5">
					<div className="flex justify-between text-[12.5px]">
						<span className="font-semibold">{__('Today', 'ai-rank-suite')}</span>
						<span className="tabular-nums" style={{ color: 'var(--ars-ink-2)' }}>
							{usd(board.spend.today)} {b.daily_usd > 0 ? `/ $${Number(b.daily_usd).toFixed(2)}` : ''} · {board.spend.today_calls} {__('calls', 'ai-rank-suite')}
						</span>
					</div>
					<Bar value={Math.min(100, todayPct)} color={`var(--ars-${tone(todayPct)})`} />
				</div>
				<div className="grid gap-1.5">
					<div className="flex justify-between text-[12.5px]">
						<span className="font-semibold">{__('This month', 'ai-rank-suite')}</span>
						<span className="tabular-nums" style={{ color: 'var(--ars-ink-2)' }}>
							{usd(board.spend.month)} {b.monthly_usd > 0 ? `/ $${Number(b.monthly_usd).toFixed(2)}` : ''} · {board.spend.month_calls} {__('calls', 'ai-rank-suite')}
						</span>
					</div>
					<Bar value={Math.min(100, monthPct)} color={`var(--ars-${tone(monthPct)})`} />
				</div>
			</div>

			{(todayPct >= 100 || monthPct >= 100) && b.hard_stop && (
				<div className="mt-3">
					<Notice tone="serious">
						{__('A budget is reached and the hard stop is on: AI calls are refused until the window rolls over or the limit is raised.', 'ai-rank-suite')}
					</Notice>
				</div>
			)}

			{board.by_day.length > 1 && (
				<div className="mt-4">
					<div className="t-overline mb-1">{__('Spend, last 30 days', 'ai-rank-suite')}</div>
					<ColumnChart
						height={90}
						data={board.by_day.map((d) => ({ label: d.day.slice(5), cost: Math.round(d.cost / 1e4) / 100 }))}
						series={[{ key: 'cost', label: __('USD', 'ai-rank-suite'), color: 'var(--ars-brand)' }]}
					/>
				</div>
			)}

			{board.by_job.length > 0 && (
				<div className="mt-4 grid gap-1">
					<div className="t-overline">{__('By job, this month', 'ai-rank-suite')}</div>
					{board.by_job.map((j) => (
						<div key={j.job} className="flex items-center justify-between gap-3 text-[12.5px] py-1" style={{ borderBottom: '1px solid var(--ars-border)' }}>
							<span className="font-medium">{j.job}</span>
							<span className="tabular-nums" style={{ color: 'var(--ars-ink-2)' }}>
								{usd(j.cost)} · {j.calls} {__('calls', 'ai-rank-suite')} · {(j.tokens / 1000).toFixed(1)}k {__('tokens', 'ai-rank-suite')} · {j.latency} ms
								{j.failed ? ` · ${j.failed} ${__('failed', 'ai-rank-suite')}` : ''}
							</span>
						</div>
					))}
				</div>
			)}

			<div className="mt-5 grid gap-3 md:grid-cols-3">
				<Field label={__('Daily limit (USD)', 'ai-rank-suite')} hint={__('0 = no limit', 'ai-rank-suite')} htmlFor="airanksuite-b-day">
					<input id="airanksuite-b-day" type="number" min="0" step="0.5" value={b.daily_usd} onChange={(e) => set('daily_usd', Number(e.target.value))} />
				</Field>
				<Field label={__('Monthly limit (USD)', 'ai-rank-suite')} hint={__('0 = no limit', 'ai-rank-suite')} htmlFor="airanksuite-b-mon">
					<input id="airanksuite-b-mon" type="number" min="0" step="1" value={b.monthly_usd} onChange={(e) => set('monthly_usd', Number(e.target.value))} />
				</Field>
				<Field label={__('Per bulk job (USD)', 'ai-rank-suite')} hint={__('A single run stops here', 'ai-rank-suite')} htmlFor="airanksuite-b-job">
					<input id="airanksuite-b-job" type="number" min="0" step="1" value={b.per_job_usd} onChange={(e) => set('per_job_usd', Number(e.target.value))} />
				</Field>
			</div>
			<div className="mt-3 flex items-center justify-between gap-3 flex-wrap">
				<div className="flex items-center gap-4 flex-wrap">
					<Switch checked={!!b.hard_stop} onChange={(v) => set('hard_stop', v)} label={__('Hard stop at the limit', 'ai-rank-suite')} />
					<label className="flex items-center gap-2 text-[12.5px]">
						{__('Warn at', 'ai-rank-suite')}
						<input type="number" min="0" max="100" style={{ width: 64 }} value={b.warn_pct} onChange={(e) => set('warn_pct', Number(e.target.value))} />%
					</label>
				</div>
				<div className="flex items-center gap-2">
					{dirty && (
						<Button variant="ghost" onClick={() => setDraft(null)} disabled={busy}>
							{__('Cancel', 'ai-rank-suite')}
						</Button>
					)}
					<Button onClick={save} busy={busy} disabled={!dirty}>
						{__('Save budget', 'ai-rank-suite')}
					</Button>
				</div>
			</div>
		</Card>
	);
}
