import { useRef, useState } from 'react';
import {
	ArrowLeft,
	Check,
	Loader2,
	Trash2,
	Plus,
	Sparkles,
	FileText,
	ExternalLink,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { TextInput } from '@/components/ui/text-input';
import { Textarea } from '@/components/ui/textarea';
import FlavioIcon from '@/components/ui/flavio-icon';
import ConfirmDialog from '@/components/ui/confirm-dialog';
import { isAppPaused } from '@/api/client';
import { resolvePageRef } from '@/features/interventions/detail/pageRef';
import { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/**
 * Detail for the `faqcontentsingle` / `propose` intervention (selection_per_page).
 *
 * Flavio proposes a FAQ section for a page; the user edits the heading and the
 * Q&A pairs inline (no edit button) and Publishes, or keeps things as they are.
 *
 * v1 scope: edit and remove pairs only — no reordering (per product) and no
 * adding net-new pairs. At least 3 pairs are required, so removing is blocked at
 * three and Publish is disabled below that.
 *
 * Contract (doc wins over the task): userResponse is
 * `{ choice:"apply", confirmed_heading, confirmed_pairs:[{question,answer}] }`.
 *
 * Defensive on metadata: every field is read with a fallback.
 */
const MIN_PAIRS = 3;

const FaqContent = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);
	// Trial ended: the intervention can't be acted on, so its action buttons are
	// swapped for the single "unlock" upgrade CTA.
	const isPaused = isAppPaused();

	const [heading, setHeading] = useState(m.proposed_heading || '');
	// The live payload keys pairs as { question, answer } (the doc says { q, a });
	// read both so we're correct either way.
	const [pairs, setPairs] = useState(() =>
		(Array.isArray(m.proposed_pairs) ? m.proposed_pairs : []).map(
			(p, i) => ({
				id: i,
				q: p?.question ?? p?.q ?? '',
				a: p?.answer ?? p?.a ?? '',
			})
		)
	);
	// Monotonic id source for new pairs, so keys stay stable across add/remove.
	const nextId = useRef(pairs.length);

	const {
		pending,
		resolved,
		error,
		confirmingDismiss,
		run,
		confirmDismiss,
		cancelDismiss,
	} = useInterventionResponse(interventionId, { onResolved });

	const updatePair = (id, field, value) =>
		setPairs((prev) =>
			prev.map((p) => (p.id === id ? { ...p, [field]: value } : p))
		);
	const removePair = (id) =>
		setPairs((prev) => prev.filter((p) => p.id !== id));
	const addPair = () => {
		const id = nextId.current;
		nextId.current += 1;
		setPairs((prev) => [...prev, { id, q: '', a: '' }]);
	};

	const enoughPairs = pairs.length >= MIN_PAIRS;
	const allComplete = pairs.every((p) => p.q.trim() && p.a.trim());
	const hasHeading = heading.trim().length > 0;
	const canPublish =
		enoughPairs && allComplete && hasHeading && !pending && !resolved;

	let reason = '';
	if (!enoughPairs) reason = `Keep at least ${MIN_PAIRS} questions to publish.`;
	else if (!hasHeading) reason = 'Add a heading for the section.';
	else if (!allComplete)
		reason = 'Fill in every question and answer, or remove the empty ones.';

	if (resolved) {
		return (
			<div className="max-w-2xl mx-auto text-center">
				<FlavioIcon className="w-12 h-12 mx-auto mb-4" />
				<h1 className="heading-h2 mt-0! leading-tight mb-3">
					{resolved === 'primary' ? 'All set' : 'Got it'}
				</h1>
				<div className="max-w-md mx-auto">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						{resolved === 'primary'
							? "Great. I'll add your FAQ section shortly."
							: "No problem. I won't add a FAQ section."}
					</p>
				</div>
				{onBack && (
					<Button
						onClick={onBack}
						size="lg"
						className="mt-6 bg-foreground text-background! hover:bg-foreground/90"
					>
						<ArrowLeft />
						Back to your list
					</Button>
				)}
			</div>
		);
	}

	return (
		<div className="max-w-2xl mx-auto">
			<div className="text-center">
				<h1 className="heading-h1 mt-0! leading-tight mb-3">
					Add an FAQ section
				</h1>
				<div className="max-w-xl mx-auto mb-8">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						Based on your top search queries, here are a few questions
						to answer. Edit anything before you publish.
					</p>
					{pageLabel &&
						(pageUrl ? (
							<a
								href={pageUrl}
								target="_blank"
								rel="noopener noreferrer"
								className="mt-3 inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 small-medium text-muted-foreground! hover:bg-muted/60 hover:text-foreground! transition-colors"
							>
								<FileText className="w-3.5 h-3.5" />
								{pageLabel}
								<ExternalLink className="w-3 h-3" />
							</a>
						) : (
							<div className="mt-3 inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 small-medium text-muted-foreground">
								<FileText className="w-3.5 h-3.5" />
								{pageLabel}
							</div>
						))}
				</div>
			</div>

			<div className="text-left mb-4">
				<p className="small-semibold uppercase tracking-wide text-muted-foreground mb-2">
					Section heading
				</p>
				<TextInput
					value={heading}
					onChange={(e) => setHeading(e.target.value)}
					error={!hasHeading}
					placeholder="Frequently asked questions"
					className="text-2xl! font-bold! h-auto! py-2.5!"
				/>
			</div>

			<div className="flex items-center gap-2 mb-3 text-left">
				<p className="small-semibold uppercase tracking-wide text-muted-foreground my-0!">
					Questions &amp; answers
				</p>
				<span
					className={`inline-flex items-center rounded-full px-2 py-0.5 small-regular ${
						enoughPairs
							? 'bg-muted text-muted-foreground'
							: 'border border-amber-200 bg-amber-50 text-amber-700'
					}`}
				>
					{pairs.length} of min. {MIN_PAIRS}
				</span>
			</div>

			<div className="space-y-6">
				{pairs.map((p, index) => (
					<div key={p.id} className="text-left">
						<div className="flex items-center justify-between mb-2">
							<span className="small-semibold tabular-nums text-muted-foreground/60">
								{String(index + 1).padStart(2, '0')}
							</span>
							<button
								type="button"
								onClick={() => removePair(p.id)}
								aria-label="Remove question"
								title="Remove question"
								className="inline-flex items-center justify-center w-8 h-8 rounded-md text-muted-foreground hover:bg-muted/60 hover:text-foreground transition-colors cursor-pointer"
							>
								<Trash2 className="w-4 h-4" />
							</button>
						</div>
						<TextInput
							value={p.q}
							onChange={(e) =>
								updatePair(p.id, 'q', e.target.value)
							}
							error={!p.q.trim()}
							placeholder="Question"
							className="font-semibold!"
						/>
						<Textarea
							value={p.a}
							onChange={(e) =>
								updatePair(p.id, 'a', e.target.value)
							}
							error={!p.a.trim()}
							rows={3}
							placeholder="Answer"
							className="mt-2"
						/>
					</div>
				))}
			</div>

			<button
				type="button"
				onClick={addPair}
				className="mt-4 w-full inline-flex items-center justify-center gap-1.5 rounded-2xl border border-dashed border-border px-4 py-3 small-medium text-muted-foreground hover:bg-muted/40 hover:text-foreground transition-colors cursor-pointer"
			>
				<Plus className="w-4 h-4" />
				Add a question
			</button>

			<div className="max-w-xl mx-auto mt-6 flex items-start justify-center gap-2 small-regular text-muted-foreground">
				<Sparkles className="w-4 h-4 shrink-0 mt-0.5" />
				<span className="text-left">
					I'll also add the FAQPage schema so this can show up as a rich
					result in Google.
				</span>
			</div>

			<div className="flex items-center justify-center gap-3 mt-8">
				{isPaused ? (
					<UpgradeLock />
				) : (
					<>
						<Button
							onClick={() =>
								run('primary', {
									status: 'acknowledge',
									userResponse: {
										choice: 'apply',
										confirmed_heading: heading,
										confirmed_pairs: pairs.map((p) => ({
											question: p.q,
											answer: p.a,
										})),
									},
								})
							}
							disabled={!canPublish}
							size="lg"
							className="bg-foreground text-background! hover:bg-foreground/90"
						>
							{pending === 'primary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<Check />
							)}
							Publish
						</Button>
						<Button
							onClick={() =>
								run('secondary', {
									status: 'dismiss',
									userResponse: { choice: 'dismiss' },
								})
							}
							disabled={!!pending || !!resolved}
							size="lg"
							variant="outline"
						>
							{pending === 'secondary' && (
								<Loader2 className="animate-spin" />
							)}
							Keep as is
						</Button>
					</>
				)}
			</div>

			{(error || reason) && (
				<p
					className={`small-regular text-center mt-3 mb-0! ${
						error ? 'text-destructive' : 'text-muted-foreground'
					}`}
				>
					{error || reason}
				</p>
			)}
			<p className="small-regular text-muted-foreground text-center mt-4 mb-0!">
				Nothing goes live until you publish.
			</p>

			<ConfirmDialog
				open={confirmingDismiss}
				onOpenChange={(open) => {
					if (!pending && !open) cancelDismiss();
				}}
				title="Dismiss this suggestion?"
				description="Nothing on your site changes, and I won't suggest this again."
				confirmLabel="Yes, dismiss"
				cancelLabel="Cancel"
				pending={pending === 'secondary'}
				onConfirm={confirmDismiss}
			/>
		</div>
	);
};

export default FaqContent;
