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

/**
 * The knowledge base: what every AI call — on every engine — is briefed with.
 *
 * Two layers, shown as two tabs. The template is fixed and identical for all
 * providers: what this plugin is, what GEO means, the house rules, and the
 * live facts about this site. The owner's layer is free text, appended after
 * it. "Preview" shows the assembled briefing exactly as the model receives
 * it, because a summary of what is being said on your behalf is not the same
 * as reading it.
 */
export default function KnowledgeBase() {
	const [data, setData] = useState(null);
	const [draft, setDraft] = useState(null);
	const [tab, setTab] = useState('custom');
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);

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

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

	const stored = data.custom || '';
	const value = draft === null ? stored : draft;
	const dirty = draft !== null && draft !== stored;

	const save = async () => {
		setBusy(true);
		setError(null);
		try {
			const next = await api.put('/ai/knowledge', { custom: value });
			setData(next);
			setDraft(null);
			setSaved(true);
			setTimeout(() => setSaved(false), 1800);
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const cancel = () => setDraft(null);

	// The fixed part of the briefing is everything before the owner's section.
	const briefing = data.briefing || '';
	const cut = briefing.indexOf("## About this business, in the owner's words");
	const fixed = cut > 0 ? briefing.slice(0, cut).trim() : briefing;

	return (
		<Card
			title={__('Knowledge base', 'ai-rank-suite')}
			subtitle={__(
				'What every AI call is told before its task — on every engine you connect. The template is fixed and always sent; your own notes are added after it.',
				'ai-rank-suite'
			)}
			icon={<IconDoc size={18} />}
			action={
				<div className="flex items-center gap-2">
					{saved && <Badge tone="good">✓ {__('Saved', 'ai-rank-suite')}</Badge>}
					<Segmented
						value={tab}
						onChange={setTab}
						options={[
							{ id: 'custom', label: __('Your notes', 'ai-rank-suite') },
							{ id: 'template', label: __('Template', 'ai-rank-suite') },
							{ id: 'preview', label: __('Preview', 'ai-rank-suite') },
						]}
					/>
				</div>
			}
		>
			{error && <Notice tone="serious">{error}</Notice>}

			{tab === 'custom' && (
				<div className="grid gap-3">
					<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
						{__(
							'Tell the writer what a new colleague would need to know: what you sell, to whom, where, in which languages, what you never claim, and how you sound. Plain text; the fixed template already covers SEO and GEO rules.',
							'ai-rank-suite'
						)}
					</p>
					<textarea
						rows={12}
						value={value}
						placeholder={data.template}
						onChange={(e) => setDraft(e.target.value)}
						style={{ fontFamily: 'inherit', fontSize: 13, lineHeight: 1.5 }}
					/>
					<div className="flex items-center justify-between gap-3 flex-wrap">
						<div className="flex items-center gap-2 flex-wrap">
							{stored === '' && (
								<Button variant="ghost" onClick={() => setDraft(data.template)}>
									{__('Start from the template', 'ai-rank-suite')}
								</Button>
							)}
							<span className="t-caption">
								{value.length.toLocaleString()} {__('characters', 'ai-rank-suite')}
							</span>
						</div>
						<div className="flex items-center gap-2">
							{dirty && (
								<Button variant="ghost" onClick={cancel} disabled={busy}>
									{__('Cancel', 'ai-rank-suite')}
								</Button>
							)}
							<Button onClick={save} busy={busy} disabled={!dirty}>
								{__('Save notes', 'ai-rank-suite')}
							</Button>
						</div>
					</div>
				</div>
			)}

			{tab === 'template' && (
				<div className="grid gap-2">
					<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
						{__(
							'Fixed for every engine and every task. The site facts in it are read live from WordPress and from the Schema → Identity settings, so filling those in makes every AI output better.',
							'ai-rank-suite'
						)}
					</p>
					<pre className="ars-briefing">{fixed}</pre>
				</div>
			)}

			{tab === 'preview' && (
				<div className="grid gap-2">
					<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-2)' }}>
						{__('The complete briefing, verbatim, as the next AI call will receive it. Each task then adds its own instructions after this.', 'ai-rank-suite')}
					</p>
					<pre className="ars-briefing">{briefing}</pre>
					{dirty && (
						<Notice tone="warning">{__('You have unsaved notes — this preview shows what is saved, not what is typed.', 'ai-rank-suite')}</Notice>
					)}
				</div>
			)}
		</Card>
	);
}
