import React, { useState } from 'react';
import { __, _n, sprintf } from '@wordpress/i18n';
import { Badge, Button, Notice } from './ui';
import { IconX } from './icons';

function Field({ field, value, onChange }) {
	const common = {
		value: value ?? '',
		placeholder: field.hint,
		onChange: (e) => onChange(e.target.value),
	};
	return (
		<div className={field.type === 'lines' ? '' : 'sm:max-w-[440px]'}>
			<label className="block font-medium mb-1 flex items-center gap-1.5">
				{field.label}
				{field.required && <Badge tone="serious">{__('required', 'ai-rank-suite')}</Badge>}
				{!field.required && field.recommended && <Badge tone="warning">{__('recommended', 'ai-rank-suite')}</Badge>}
			</label>
			{field.type === 'lines' ? (
				<textarea rows={4} {...common} />
			) : field.type === 'select' ? (
				<select value={value ?? ''} onChange={(e) => onChange(e.target.value)}>
					<option value="">—</option>
					{field.options.map((o) => (
						<option key={o} value={o}>
							{o}
						</option>
					))}
				</select>
			) : (
				<input type={field.type === 'date' || field.type === 'datetime-local' ? field.type : 'text'} {...common} />
			)}
			{field.hint && field.type !== 'lines' && (
				<div className="text-[11.5px] mt-1" style={{ color: 'var(--ars-ink-3)' }}>
					{field.hint}
				</div>
			)}
		</div>
	);
}

export function TypePicker({ grouped, value, onChange }) {
	const [search, setSearch] = useState('');
	const q = search.trim().toLowerCase();

	const filtered = Object.entries(grouped || {})
		.map(([group, entries]) => [group, entries.filter((e) => !q || e.label.toLowerCase().includes(q))])
		.filter(([, entries]) => entries.length > 0);

	return (
		<div className="grid gap-2 sm:max-w-[440px]">
			<input
				type="text"
				placeholder={__('Search 77 schema types…', 'ai-rank-suite')}
				value={search}
				onChange={(e) => setSearch(e.target.value)}
			/>
			<select value={value} onChange={(e) => onChange(e.target.value)} size={q ? 8 : undefined}>
				{filtered.map(([group, entries]) => (
					<optgroup key={group} label={group}>
						{entries.map((e) => (
							<option key={e.value} value={e.value}>
								{e.label}
							</option>
						))}
					</optgroup>
				))}
			</select>
		</div>
	);
}

export default function SchemaEditor({ data, onChange, showVariables = true }) {
	const items = data?.items || [];
	const types = data?.types || {};
	const validation = data?.validation || [];

	const setItem = (index, patch) =>
		onChange(items.map((it, i) => (i === index ? { ...it, ...patch } : it)));

	const firstType = Object.keys(data?.grouped?.[Object.keys(data?.grouped || {})[0]] || {}).length
		? Object.values(data.grouped)[0][0].value
		: 'Article';

	return (
		<div className="grid gap-4">
			{data?.templates?.length > 0 && (
				<Notice>
					{data.templates.length === 1
						? sprintf(__('The template “%1$s” also applies %2$s schema to this page.', 'ai-rank-suite'), data.templates[0].name, data.templates[0].type)
						: sprintf(__('%d global templates also apply schema to this page.', 'ai-rank-suite'), data.templates.length)}
				</Notice>
			)}

			{items.length === 0 && (
				<p className="m-0 text-[13px]" style={{ color: 'var(--ars-ink-2)' }}>{__('No custom schema on this page yet — Article/WebPage and breadcrumbs are always emitted automatically.', 'ai-rank-suite')}</p>
			)}

			{items.map((item, index) => {
				const type = types[item.type];
				const check = validation[index];
				return (
					<div key={index} className="ars-r-md p-4" style={{ background: 'var(--ars-surface-2)' }}>
						<div className="flex items-start justify-between gap-3 mb-3">
							<div className="flex items-center gap-2 flex-wrap">
								<span className="font-semibold text-[13.5px]">{type?.label || item.type}</span>
								{check && !check.valid && <Badge tone="serious">{sprintf(__('%d required missing', 'ai-rank-suite'), check.missing_required.length)}</Badge>}
								{check && check.valid && check.missing_recommended.length > 0 && (
									<Badge tone="warning">{sprintf(__('%d recommended missing', 'ai-rank-suite'), check.missing_recommended.length)}</Badge>
								)}
								{check && check.valid && check.missing_recommended.length === 0 && <Badge tone="good">✓ {__('complete', 'ai-rank-suite')}</Badge>}
							</div>
							<button
								type="button"
								aria-label={__('Remove schema', 'ai-rank-suite')}
								className="border-0 bg-transparent cursor-pointer"
								style={{ color: 'var(--ars-ink-3)' }}
								onClick={() => onChange(items.filter((_, i) => i !== index))}
							>
								<IconX size={15} />
							</button>
						</div>

						<div className="grid gap-3">
							<TypePicker
								grouped={data.grouped}
								value={item.type}
								onChange={(next) => setItem(index, { type: next, data: {} })}
							/>

							{check && check.missing_required.length > 0 && (
								<Notice tone="serious">
									{sprintf(__('Google will ignore this schema until you fill in: %s.', 'ai-rank-suite'), check.missing_required.join(', '))}
								</Notice>
							)}

							{(type?.fields || []).map((field) => (
								<Field
									key={field.key}
									field={field}
									value={item.data?.[field.key]}
									onChange={(value) => setItem(index, { data: { ...item.data, [field.key]: value } })}
								/>
							))}
						</div>
					</div>
				);
			})}

			<div className="flex items-center gap-2 flex-wrap">
				<Button
					variant="ghost"
					onClick={() => onChange([...items, { type: firstType, data: {} }])}
					disabled={items.length >= 20}
				>
					+ {__('Add schema', 'ai-rank-suite')}
				</Button>
				{showVariables && (
					<details className="text-[12px]">
						<summary className="cursor-pointer" style={{ color: 'var(--ars-ink-2)' }}>{__('Available variables', 'ai-rank-suite')}</summary>
						<div className="flex flex-wrap gap-1.5 mt-2">
							{Object.entries(data?.variables || {}).map(([token, label]) => (
								<code
									key={token}
									className="ars-mono px-1.5 py-0.5 rounded"
									style={{ background: 'var(--ars-surface-2)' }}
									title={label}
								>
									{token}
								</code>
							))}
						</div>
					</details>
				)}
			</div>

			{data?.preview?.length > 0 && (
				<details>
					<summary className="cursor-pointer text-[12.5px] font-medium">
						{sprintf(_n('Preview JSON-LD (%d node)', 'Preview JSON-LD (%d nodes)', data.preview.length, 'ai-rank-suite'), data.preview.length)}
					</summary>
					<pre
						className="ars-mono m-0 mt-2 p-3 ars-r-md overflow-auto"
						style={{ background: 'var(--ars-surface-2)', maxHeight: 300 }}
					>
						{JSON.stringify(data.preview, null, 2)}
					</pre>
				</details>
			)}
		</div>
	);
}
