import { useState } from 'react';
import {
	ArrowLeft,
	Check,
	Loader2,
	FileText,
	ExternalLink,
	AlertTriangle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import FlavioIcon from '@/components/ui/flavio-icon';
import ConfirmDialog from '@/components/ui/confirm-dialog';
import { RichTextEditor, RichTextView } from '@/components/ui/rich-text-editor';
import { isAppPaused } from '@/api/client';
import { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import { resolvePageRef } from '@/features/interventions/detail/pageRef';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/**
 * Detail for the `improvecontentsingle` / `propose` intervention (type selection).
 * This handler has a single variant.
 *
 * Flavio rewrites a core page's content; the user reviews/edits it in the plugin's
 * own WYSIWYG (not the WP block editor) and Publishes, or keeps the current one.
 * Three tabs: Edit (the editor), Current (the existing content, read-only) and
 * Preview (the edited content, read-only).
 *
 * Contract userResponse: { choice:"apply", confirmed_content }. Publish →
 * `acknowledge` with the edited HTML; secondary action → `dismiss`.
 *
 * Defensive on metadata: every field is read with a fallback.
 */

const TABS = [
	{ id: 'edit', label: 'Edit' },
	{ id: 'current', label: 'Current' },
	{ id: 'preview', label: 'Preview' },
];

const ImproveContent = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const { pageLabel, pageUrl } = resolvePageRef(m);
	const warnings = Array.isArray(m.warnings) ? m.warnings : [];
	const summary =
		m.change_summary ||
		'I made it shorter, more specific, and easier to read.';

	const [content, setContent] = useState(m.proposed_content_raw || '');
	const [tab, setTab] = useState('edit');

	// 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 {
		pending,
		resolved,
		error,
		confirmingDismiss,
		run,
		confirmDismiss,
		cancelDismiss,
	} = useInterventionResponse(interventionId, { onResolved });

	const isEmpty = content.replace(/<[^>]*>/g, '').trim() === '';
	const canPublish = !isEmpty && !pending && !resolved;

	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 publish your rewritten page shortly."
							: 'No problem. I’ll keep your current content.'}
					</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-3xl mx-auto">
			<div className="text-center">
				<h1 className="heading-h1 mt-0! leading-tight mb-3">
					Approve your rewritten content
				</h1>
				<div className="max-w-xl mx-auto mb-6">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						{summary} Tweak 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 className="inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 p-1 mb-5">
					{TABS.map((t) => (
						<button
							key={t.id}
							type="button"
							onClick={() => setTab(t.id)}
							className={`rounded-full px-4 py-1.5 small-medium transition-colors cursor-pointer ${
								tab === t.id
									? 'bg-background text-foreground shadow-sm'
									: 'text-muted-foreground hover:text-foreground'
							}`}
						>
							{t.label}
						</button>
					))}
				</div>
			</div>

			{tab === 'edit' && (
				<RichTextEditor value={content} onChange={setContent} />
			)}
			{tab === 'current' &&
				(m.current_content_raw ? (
					<RichTextView html={m.current_content_raw} />
				) : (
					<div className="rounded-2xl border border-border px-6 py-8 text-center">
						<p className="paragraph-regular italic text-muted-foreground/70 my-0!">
							This page has no content yet.
						</p>
					</div>
				))}
			{tab === 'preview' && <RichTextView html={content} />}

			{warnings.length > 0 && (
				<div className="mt-4 flex items-start gap-2 rounded-xl border border-amber-200 bg-amber-50 p-3 text-left small-regular text-amber-800">
					<AlertTriangle className="w-4 h-4 shrink-0 mt-0.5 text-amber-600" />
					<div>
						{warnings.map((w, i) => (
							<p key={i} className="my-0! [&+p]:mt-1!">
								{typeof w === 'string' ? w : w?.message || ''}
							</p>
						))}
					</div>
				</div>
			)}

			<div className="flex items-center justify-center gap-3 mt-8">
				{isPaused ? (
					<UpgradeLock />
				) : (
					<>
						<Button
							onClick={() =>
								run('primary', {
									status: 'acknowledge',
									userResponse: {
										choice: 'apply',
										confirmed_content: content,
									},
								})
							}
							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 && (
				<p className="small-regular text-destructive text-center mt-3 mb-0!">
					{error}
				</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 ImproveContent;
