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

/**
 * Comma-separated list editor.
 *
 * A repeater with add/remove buttons per row looks more serious and is slower
 * to use for exactly the fields people paste from somewhere else. One field,
 * commas, and a live chip preview so nothing is silently mangled.
 */
function ListField({ label, hint, value, onChange, placeholder }) {
	const [text, setText] = useState((value || []).join(', '));
	useEffect(() => {
		setText((value || []).join(', '));
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [JSON.stringify(value || [])]);

	const commit = (raw) => {
		setText(raw);
		onChange(
			raw
				.split(',')
				.map((s) => s.trim())
				.filter(Boolean)
		);
	};

	const chips = text
		.split(',')
		.map((s) => s.trim())
		.filter(Boolean);

	return (
		<div>
			<label className="block font-medium mb-1">{label}</label>
			<input type="text" value={text} placeholder={placeholder} onChange={(e) => commit(e.target.value)} />
			{hint && (
				<p className="m-0 mt-1 text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>
					{hint}
				</p>
			)}
			{chips.length > 0 && (
				<div className="flex flex-wrap gap-1 mt-1.5">
					{chips.map((c, i) => (
						<span
							key={`${c}-${i}`}
							className="text-[11px] px-1.5 py-0.5"
							style={{
								background: 'var(--ars-surface-3)',
								color: 'var(--ars-ink-2)',
								borderRadius: 'var(--ars-r-xs)',
							}}
						>
							{c}
						</span>
					))}
				</div>
			)}
		</div>
	);
}

export default function Identity() {
	const [data, setData] = useState(null);
	const [id, setId] = useState(null);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);
	const [showJson, setShowJson] = useState(false);

	useEffect(() => {
		api
			.get('/settings/schema')
			.then((d) => {
				setData(d);
				setId(d.settings.identity || {});
			})
			.catch((e) => setError(e.message));
	}, []);

	const set = (patch) => setId((prev) => ({ ...prev, ...patch }));

	const save = async () => {
		setBusy(true);
		setError(null);
		try {
			// Only the fields this screen owns. Spreading the whole settings
			// snapshot would revert anything changed on the Overview tab since
			// this component mounted — the same clobber, in the other direction.
			const next = await api.put('/settings/schema', {
				identity: id,
				org_type: data.settings.org_type,
				org_name: data.settings.org_name,
			});
			setData(next);
			setId(next.settings.identity || {});
			setSaved(true);
			setTimeout(() => setSaved(false), 2400);
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const typeGroups = useMemo(() => Object.entries(data?.types || {}), [data]);

	if (!data || !id) return <PageState error={error} />;

	const entity = data.entity || { score: 0, missing: [] };
	const identifiers = Object.entries(data.identifiers || {});
	const policies = Object.entries(data.policies || {});
	const contactTypes = data.contactTypes || {};
	const contacts = id.contacts || [];

	const setContact = (i, patch) =>
		set({ contacts: contacts.map((c, j) => (i === j ? { ...c, ...patch } : c)) });

	return (
		<div className="grid gap-4">
			<Card
				title={__('Entity identity', 'ai-rank-suite')}
				subtitle={__('Who is answering — the node a knowledge graph resolves you to', 'ai-rank-suite')}
				action={
					<Button onClick={save} busy={busy}>{__('Save identity', 'ai-rank-suite')}</Button>
				}
			>
				<div className="grid gap-4 md:grid-cols-[auto_1fr] items-start">
					<div className="grid place-items-center">
						<ScoreRing value={entity.score} label={__('Entity strength', 'ai-rank-suite')} size={128} />
					</div>
					<div className="grid gap-3">
						<Explain title={__('Why this matters more than any other schema setting', 'ai-rank-suite')} open={entity.score < 50}>
							<p>
								{__('A search engine ranks pages. An assistant answers a question, and to answer it, it has to decide whose answer to repeat. That decision runs on entities — a resolved, cross-referenced thing in a knowledge graph — not on keywords.', 'ai-rank-suite')}
							</p>
							<p>
								<code>{__('Organization + name + logo', 'ai-rank-suite')}</code> {__('does not resolve to anything; it is a label. Registration identifiers, links to profiles the graph already holds, and an explicit list of the subjects you claim expertise in are what turn a label into an entity that can be cited by name.', 'ai-rank-suite')}
							</p>
						</Explain>

						{entity.missing.length > 0 && (
							<div className="grid gap-1.5">
								<div className="t-overline">{__('Worth adding, strongest first', 'ai-rank-suite')}</div>
								{entity.missing.slice(0, 4).map((m) => (
									<div
										key={m.key}
										className="px-3 py-2"
										style={{ background: 'var(--ars-surface-2)', borderRadius: 'var(--ars-r-sm)' }}
									>
										<div className="font-semibold text-[12.5px]">{m.label}</div>
										<div className="text-[11.5px] mt-0.5" style={{ color: 'var(--ars-ink-2)' }}>
											{m.why}
										</div>
									</div>
								))}
							</div>
						)}
						{entity.missing.length === 0 && <Notice tone="good">{__('Every high-value entity field is filled in.', 'ai-rank-suite')}</Notice>}
					</div>
				</div>
				{error && <Notice tone="serious">{error}</Notice>}
				{saved && <Badge tone="good">✓ Saved</Badge>}
			</Card>

			<Card title={__('What kind of organization', 'ai-rank-suite')} subtitle={__('The subtype decides which properties Google will read', 'ai-rank-suite')}>
				<div className="grid gap-3">
					<div className="grid gap-3 sm:grid-cols-2">
						<div>
							<label className="block font-medium mb-1">{__('Type', 'ai-rank-suite')}</label>
							<select
								value={data.settings.org_type}
								onChange={(e) => setData({ ...data, settings: { ...data.settings, org_type: e.target.value } })}
							>
								{typeGroups.map(([group, types]) => (
									<optgroup key={group} label={group}>
										{Object.entries(types).map(([value, label]) => (
											<option key={value} value={value}>
												{label}
											</option>
										))}
									</optgroup>
								))}
							</select>
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Public name', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={data.settings.org_name}
								placeholder={__('Falls back to the site title', 'ai-rank-suite')}
								onChange={(e) => setData({ ...data, settings: { ...data.settings, org_name: e.target.value } })}
							/>
						</div>
					</div>

					<MediaPicker
						label={__('Organization logo', 'ai-rank-suite')}
						title={__('Select the organization logo', 'ai-rank-suite')}
						value={id.logo || ''}
						onChange={(url) => set({ logo: url })}
						hint={__('What Google shows beside your name in a Knowledge Panel. Square, at least 112×112px. Without one, the site icon (favicon) is used — rarely how a brand wants to appear.', 'ai-rank-suite')}
					/>

					<div className="grid gap-3 sm:grid-cols-2">
						<div>
							<label className="block font-medium mb-1">{__('Legal name', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={id.legal_name || ''}
								placeholder={__('The name on the register', 'ai-rank-suite')}
								onChange={(e) => set({ legal_name: e.target.value })}
							/>
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Also known as', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={id.alt_name || ''}
								placeholder={__('Trading name, abbreviation', 'ai-rank-suite')}
								onChange={(e) => set({ alt_name: e.target.value })}
							/>
						</div>
					</div>

					<div>
						<label className="block font-medium mb-1">{__('Description', 'ai-rank-suite')}</label>
						<textarea
							rows={2}
							value={id.description || ''}
							placeholder={__('The sentence an assistant repeats when asked who you are.', 'ai-rank-suite')}
							onChange={(e) => set({ description: e.target.value })}
						/>
					</div>

					<div className="grid gap-3 sm:grid-cols-3">
						<div>
							<label className="block font-medium mb-1">{__('Founded', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={id.founded || ''}
								placeholder="2016-04-01"
								onChange={(e) => set({ founded: e.target.value })}
							/>
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Founder', 'ai-rank-suite')}</label>
							<input type="text" value={id.founder || ''} onChange={(e) => set({ founder: e.target.value })} />
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Employees', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={id.employees || ''}
								placeholder="45"
								onChange={(e) => set({ employees: e.target.value })}
							/>
						</div>
					</div>

					<div className="grid gap-3 sm:grid-cols-3">
						<div>
							<label className="block font-medium mb-1">{__('Public email', 'ai-rank-suite')}</label>
							<input type="text" value={id.email || ''} onChange={(e) => set({ email: e.target.value })} />
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Public phone', 'ai-rank-suite')}</label>
							<input type="text" value={id.phone || ''} onChange={(e) => set({ phone: e.target.value })} />
						</div>
						<div>
							<label className="block font-medium mb-1">{__('Price range', 'ai-rank-suite')}</label>
							<input
								type="text"
								value={id.price_range || ''}
								placeholder="$$"
								onChange={(e) => set({ price_range: e.target.value })}
							/>
						</div>
					</div>
				</div>
			</Card>

			<Card title={__('How the graph finds you', 'ai-rank-suite')} subtitle={__('sameAs and knowsAbout do more for citation than every other field combined', 'ai-rank-suite')}>
				<div className="grid gap-4">
					<ListField
						label={__('Profiles (sameAs)', 'ai-rank-suite')}
						hint={__('One URL per profile: LinkedIn, Wikidata, Crunchbase, Companies House, Google Business, industry directories.', 'ai-rank-suite')}
						placeholder="https://linkedin.com/company/…, https://www.wikidata.org/wiki/…"
						value={id.same_as}
						onChange={(v) => set({ same_as: v })}
					/>
					<ListField
						label={__('Subjects you know (knowsAbout)', 'ai-rank-suite')}
						hint={__('The topics you claim expertise in. Be specific: “orthopaedic physiotherapy” beats “health”.', 'ai-rank-suite')}
						placeholder={__('dermatology, orthopaedics, sports injury rehabilitation', 'ai-rank-suite')}
						value={id.knows_about}
						onChange={(v) => set({ knows_about: v })}
					/>
					<div className="grid gap-4 sm:grid-cols-2">
						<ListField
							label={__('Areas served', 'ai-rank-suite')}
							hint={__('Country codes or region names — assistants filter by geography before quality.', 'ai-rank-suite')}
							placeholder={__('AE, SA, QA', 'ai-rank-suite')}
							value={id.area_served}
							onChange={(v) => set({ area_served: v })}
						/>
						<ListField
							label={__('Languages', 'ai-rank-suite')}
							placeholder={__('en, ar, de', 'ai-rank-suite')}
							value={id.languages}
							onChange={(v) => set({ languages: v })}
						/>
					</div>
					<div className="grid gap-4 sm:grid-cols-2">
						<ListField
							label={__('Currencies accepted', 'ai-rank-suite')}
							placeholder={__('AED, EUR, USD', 'ai-rank-suite')}
							value={id.currencies}
							onChange={(v) => set({ currencies: v })}
						/>
						<ListField
							label={__('Payment methods', 'ai-rank-suite')}
							placeholder={__('Cash, Visa, Mastercard, Apple Pay', 'ai-rank-suite')}
							value={id.payments}
							onChange={(v) => set({ payments: v })}
						/>
					</div>
					<div className="grid gap-4 sm:grid-cols-2">
						<ListField
							label={__('Awards', 'ai-rank-suite')}
							placeholder={__('Best Clinic 2024', 'ai-rank-suite')}
							value={id.awards}
							onChange={(v) => set({ awards: v })}
						/>
						<ListField
							label={__('Certifications & accreditations', 'ai-rank-suite')}
							placeholder={__('ISO 9001, JCI Accredited', 'ai-rank-suite')}
							value={id.certifications}
							onChange={(v) => set({ certifications: v })}
						/>
					</div>
					<div className="grid gap-4 sm:grid-cols-2">
						<ListField
							label={__('Member of', 'ai-rank-suite')}
							placeholder={__('Dubai Chamber of Commerce', 'ai-rank-suite')}
							value={id.member_of}
							onChange={(v) => set({ member_of: v })}
						/>
						<div>
							<label className="block font-medium mb-1">{__('Parent organization', 'ai-rank-suite')}</label>
							<input type="text" value={id.parent_org || ''} onChange={(e) => set({ parent_org: e.target.value })} />
						</div>
					</div>
				</div>
			</Card>

			<Card
				title={__('Registration identifiers', 'ai-rank-suite')}
				subtitle={__('What turns a claimed business into a verifiable one — fill in whichever your market uses', 'ai-rank-suite')}
			>
				<div className="grid gap-3 sm:grid-cols-2">
					{identifiers.map(([key, def]) => (
						<div key={key}>
							<label className="block font-medium mb-1 flex items-center gap-1.5">
								{def.label}
								<span
									className="ars-tag"
									style={{
										background: 'var(--ars-surface-3)',
										color: 'var(--ars-ink-3)',
									}}
								>
									{def.region}
								</span>
							</label>
							<input
								type="text"
								value={(id.identifiers || {})[key] || ''}
								placeholder={def.hint}
								onChange={(e) => set({ identifiers: { ...(id.identifiers || {}), [key]: e.target.value } })}
							/>
						</div>
					))}
				</div>
			</Card>

			<Card title={__('Contact points', 'ai-rank-suite')} subtitle={__('Per role, per language, per market — this is what makes you resolvable in each country', 'ai-rank-suite')}>
				<div className="grid gap-3">
					{contacts.length === 0 && (
						<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>{__('No contact points yet. One per role beats a single switchboard number.', 'ai-rank-suite')}</p>
					)}
					{contacts.map((c, i) => (
						<div
							key={i}
							className="grid gap-2 p-3"
							style={{ background: 'var(--ars-surface-2)', borderRadius: 'var(--ars-r-sm)' }}
						>
							<div className="grid gap-2 sm:grid-cols-3">
								<select value={c.type || 'customer support'} onChange={(e) => setContact(i, { type: e.target.value })}>
									{Object.entries(contactTypes).map(([value, label]) => (
										<option key={value} value={value}>
											{label}
										</option>
									))}
								</select>
								<input
									type="text"
									placeholder={__('Phone', 'ai-rank-suite')}
									value={c.phone || ''}
									onChange={(e) => setContact(i, { phone: e.target.value })}
								/>
								<input
									type="text"
									placeholder={__('Email', 'ai-rank-suite')}
									value={c.email || ''}
									onChange={(e) => setContact(i, { email: e.target.value })}
								/>
							</div>
							<div className="grid gap-2 sm:grid-cols-2">
								<input
									type="text"
									placeholder={__('Languages — en, ar', 'ai-rank-suite')}
									value={(c.languages || []).join(', ')}
									onChange={(e) =>
										setContact(i, {
											languages: e.target.value
												.split(',')
												.map((s) => s.trim())
												.filter(Boolean),
										})
									}
								/>
								<input
									type="text"
									placeholder={__('Areas — AE, SA', 'ai-rank-suite')}
									value={(c.areas || []).join(', ')}
									onChange={(e) =>
										setContact(i, {
											areas: e.target.value
												.split(',')
												.map((s) => s.trim())
												.filter(Boolean),
										})
									}
								/>
							</div>
							{/* Bare red text was the only control on the page with no shape.
							    A chip, like every other in-row action. */}
							<div>
								<button
									type="button"
									className="ars-chip"
									style={{ color: 'var(--ars-serious)' }}
									onClick={() => set({ contacts: contacts.filter((_, j) => j !== i) })}
								>{__('Remove', 'ai-rank-suite')}</button>
							</div>
						</div>
					))}
					<div>
						<Button
							variant="ghost"
							onClick={() => set({ contacts: [...contacts, { type: 'customer support', phone: '', email: '' }] })}
						>{__('Add a contact point', 'ai-rank-suite')}</Button>
					</div>
				</div>
			</Card>

			<Card title={__('Trust & editorial policies', 'ai-rank-suite')} subtitle={__('What Google reads for E-E-A-T, and what news surfaces require', 'ai-rank-suite')}>
				<div className="grid gap-3 sm:grid-cols-2">
					{policies.map(([key, def]) => (
						<div key={key}>
							<label className="block font-medium mb-1">{def.label}</label>
							<input
								type="text"
								placeholder="https://…"
								value={(id.policies || {})[key] || ''}
								onChange={(e) => set({ policies: { ...(id.policies || {}), [key]: e.target.value } })}
							/>
							<p className="m-0 mt-1 text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>
								{def.hint}
							</p>
						</div>
					))}
				</div>
			</Card>

			<Card
				title={__('What ships', 'ai-rank-suite')}
				subtitle={__('The exact properties merged into your Organization node', 'ai-rank-suite')}
				action={
					<Button variant="ghost" onClick={() => setShowJson(!showJson)}>
						{showJson ? 'Hide' : 'Show'} JSON-LD
					</Button>
				}
			>
				{showJson ? (
					<pre
						className="ars-mono m-0 p-3 overflow-auto text-[11.5px]"
						style={{ background: 'var(--ars-surface-2)', borderRadius: 'var(--ars-r-sm)', maxHeight: 420 }}
					>
						{JSON.stringify(data.preview || {}, null, 2)}
					</pre>
				) : (
					<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>
						{Object.keys(data.preview || {}).length} properties are currently attached to your identity node. Save to
						refresh.
					</p>
				)}
			</Card>

			<div className="flex items-center gap-2">
				<Button onClick={save} busy={busy}>{__('Save identity', 'ai-rank-suite')}</Button>
				{saved && <Badge tone="good">✓ Saved</Badge>}
			</div>
		</div>
	);
}
