import { useEffect, 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 { RichTextView } from '@/components/ui/rich-text-editor';
import { get, post, withQuery, 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` / `classic_preview` intervention.
 *
 * Classic Editor pages: the rewritten content already lives in a native WP
 * autosave (the live page is untouched). The "Draft" card shows the proposed
 * text and offers "Open live preview" (WP's own preview: their theme, their
 * shortcodes rendering); the user then Publishes or discards. Editing happens
 * after publishing, in their usual editor.
 *
 * The preview URL is minted per click by GET /content-preview-link (the nonce
 * belongs to the viewer's wp-admin session and expires, so it can never travel
 * in the intervention metadata).
 *
 * Contract userResponse: { choice:"apply", autosave_id, proposal_hash }. The
 * executor promotes the autosave verified by hash; the proposal HTML shown
 * here is display-only. On dismiss we also fire a best-effort
 * discard_content_proposal so the autosave does not linger (dismissals never
 * reach the executor).
 */

const ImproveContentClassic = ({
	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 rewrote this page to make it clearer and more specific.';

	const [previewPending, setPreviewPending] = useState(false);
	const [previewError, setPreviewError] = useState(null);
	const [previewGone, setPreviewGone] = useState(false);

	const isPaused = isAppPaused();

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

	// Best-effort cleanup after a confirmed dismiss: drop the autosave and its
	// proposal meta. Failures are fine, the plugin's 30-day GC sweeps leftovers.
	useEffect(() => {
		if (resolved === 'secondary' && m.wp_post_id) {
			post('/action', {
				action: 'discard_content_proposal',
				post_id: m.wp_post_id,
			}).catch(() => {});
		}
	}, [resolved, m.wp_post_id]);

	const openPreview = async () => {
		if (previewPending || previewGone) return;
		setPreviewPending(true);
		setPreviewError(null);
		// Open the tab synchronously so popup blockers allow it, then point it
		// at the freshly minted preview URL.
		const win = window.open('', '_blank');
		try {
			const res = await get(
				withQuery('/content-preview-link', { post_id: m.wp_post_id })
			);
			if (res?.preview_url && win) {
				win.location = res.preview_url;
			} else if (win) {
				win.close();
			}
		} catch (err) {
			if (win) win.close();
			if (err?.statusCode === 404 || err?.statusCode === 409) {
				setPreviewGone(true);
				setPreviewError(
					'The draft is no longer available. You can still discard this suggestion.'
				);
			} else {
				setPreviewError(
					'Could not open the preview. Please try again.'
				);
			}
		} finally {
			setPreviewPending(false);
		}
	};

	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">
					Review your rewritten page
				</h1>
				<div className="max-w-xl mx-auto mb-6">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						{summary} I saved it as a draft, so nothing on your live
						page has changed yet.
					</p>
				</div>
			</div>

			<div className="rounded-2xl border border-border overflow-hidden text-left">
				<div className="flex flex-wrap items-center gap-3 border-b border-border bg-muted/40 px-4 py-3">
					<span className="small-semibold uppercase tracking-wide text-magenta-600">
						Draft
					</span>
					{pageLabel &&
						(pageUrl ? (
							<a
								href={pageUrl}
								target="_blank"
								rel="noopener noreferrer"
								className="inline-flex items-center gap-1.5 rounded-full border border-border bg-background 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}
							</a>
						) : (
							<span className="inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-3 py-1 small-medium text-muted-foreground">
								<FileText className="w-3.5 h-3.5" />
								{pageLabel}
							</span>
						))}
					<div className="ml-auto">
						<Button
							onClick={openPreview}
							disabled={previewPending || previewGone}
							size="sm"
							variant="outline"
						>
							{previewPending ? (
								<Loader2 className="animate-spin" />
							) : (
								<ExternalLink />
							)}
							Open live preview
						</Button>
					</div>
				</div>

				<div className="px-6 py-5">
					{m.proposed_content_raw ? (
						<RichTextView html={m.proposed_content_raw} bare />
					) : (
						<p className="paragraph-regular italic text-muted-foreground/70 my-0!">
							The draft could not be loaded.
						</p>
					)}
				</div>

				<button
					type="button"
					onClick={openPreview}
					disabled={previewPending || previewGone}
					className="flex w-full items-center gap-2 border-t border-border bg-muted/40 px-4 py-2.5 small-regular text-muted-foreground text-left cursor-pointer hover:text-foreground transition-colors disabled:cursor-default disabled:hover:text-muted-foreground"
				>
					{previewPending ? (
						<Loader2 className="w-3.5 h-3.5 shrink-0 animate-spin" />
					) : (
						<ExternalLink className="w-3.5 h-3.5 shrink-0" />
					)}
					Live preview opens on your real site, with your theme and
					shortcodes working.
				</button>
			</div>

			{previewError && (
				<p className="small-regular text-destructive text-center mt-3 mb-0!">
					{previewError}
				</p>
			)}

			{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',
										autosave_id: m.autosave_id,
										proposal_hash: m.proposal_hash,
									},
								})
							}
							disabled={!!pending || !!resolved || previewGone}
							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" />
							)}
							Don't apply
						</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. You can edit the page
				afterwards in your usual editor.
			</p>

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

export default ImproveContentClassic;
