import { useState } from 'react';
import { ArrowLeft, Check, Loader2, Link2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { TextInput } from '@/components/ui/text-input';
import { RichTextEditor } from '@/components/ui/rich-text-editor';
import FlavioIcon from '@/components/ui/flavio-icon';
import ConfirmDialog from '@/components/ui/confirm-dialog';
import { getWordPressConfig, isAppPaused } from '@/api/client';
import { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/**
 * Detail for the `existcontact` / `create` intervention (type selection,
 * phase 2 after the shared `contact` form). Flavio drafts a brand-new contact
 * page (title + HTML body) using the contact data already in business_info;
 * the user reviews, can edit the title and the content, then applies or
 * dismisses.
 *
 * Contract metadata: `language`, `proposed_slug`, `proposed_title`,
 * `proposed_content` (HTML body), `ai:{…}`. options:[apply, dismiss].
 * `proposed_slug` is **not** editable: Flavio picks it so the page is
 * rediscoverable via `discovery/defaults` on the next scan.
 *
 * userResponse: `{ choice:"apply", confirmed_title?, confirmed_content? }`.
 * Confirmed fields are optional — when omitted the executor falls back to the
 * proposed values. We always send both since the user has been on the form.
 *
 * Defensive on metadata: every field is read with a fallback.
 */

/** Strip tags so we can check if the rich body is meaningfully non-empty. */
const isEmptyHtml = (html = '') =>
	html.replace(/<[^>]*>/g, '').trim().length === 0;

const CreateContact = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const proposedSlug = m.proposed_slug || 'contact';
	const proposedTitle = m.proposed_title || '';
	const proposedContent = m.proposed_content || '';

	// 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 siteUrl = getWordPressConfig()?.siteUrl || '';
	const pageUrl = siteUrl
		? `${siteUrl.replace(/\/$/, '')}/${proposedSlug.replace(/^\//, '')}`
		: `/${proposedSlug.replace(/^\//, '')}`;
	// Compact display: strip scheme. Trailing path stays as-is.
	const displayUrl = pageUrl.replace(/^https?:\/\//, '');

	const [title, setTitle] = useState(proposedTitle);
	const [content, setContent] = useState(proposedContent);

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

	const titleOk = title.trim().length > 0;
	const contentOk = !isEmptyHtml(content);
	const canCreate = titleOk && contentOk && !pending && !resolved;

	const create = () =>
		run('primary', {
			status: 'acknowledge',
			userResponse: {
				choice: 'apply',
				confirmed_title: title.trim(),
				confirmed_content: content,
			},
		});

	const dismiss = () =>
		run('secondary', {
			status: 'dismiss',
			userResponse: { choice: 'dismiss' },
		});

	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 contact page shortly."
							: "No problem. I won't create a contact page."}
					</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">
					Create your contact page
				</h1>
				<div className="max-w-xl mx-auto mb-3">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						I drafted a contact page using your business details. Edit
						the title or content before you publish.
					</p>
				</div>
				<div className="inline-flex items-center gap-2 rounded-full border border-border px-3 py-1 small-medium text-muted-foreground mb-8">
					<Link2 className="w-3.5 h-3.5" />
					<span className="text-muted-foreground/70">
						It will live at
					</span>
					<span className="font-mono text-foreground">
						{displayUrl}
					</span>
				</div>
			</div>

			{/* Title */}
			<div className="text-left mb-5">
				<p className="small-semibold uppercase tracking-wide text-muted-foreground mb-2 my-0!">
					Page title
				</p>
				<TextInput
					value={title}
					onChange={(e) => setTitle(e.target.value)}
					error={!titleOk}
					placeholder="Contact us"
					className="text-2xl! font-bold! h-auto! py-2.5!"
				/>
			</div>

			{/* Content */}
			<div className="text-left">
				<p className="small-semibold uppercase tracking-wide text-muted-foreground mb-2 my-0!">
					Page content
				</p>
				<RichTextEditor
					value={content}
					onChange={(html) => setContent(html)}
				/>
			</div>

			<div className="flex items-center justify-center gap-3 mt-8">
				{isPaused ? (
					<UpgradeLock />
				) : (
					<>
						<Button
							onClick={create}
							disabled={!canCreate}
							size="lg"
							className="bg-foreground text-background! hover:bg-foreground/90"
						>
							{pending === 'primary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<Check />
							)}
							Create page
						</Button>
						<Button
							onClick={dismiss}
							disabled={!!pending || !!resolved}
							size="lg"
							variant="outline"
						>
							{pending === 'secondary' && (
								<Loader2 className="animate-spin" />
							)}
							Dismiss
						</Button>
					</>
				)}
			</div>

			{!isPaused && (error || !canCreate) && (
				<p
					className={`small-regular text-center mt-3 mb-0! ${
						error ? 'text-destructive' : 'text-muted-foreground'
					}`}
				>
					{error ||
						(!titleOk && !contentOk
							? 'Add a title and some content before publishing.'
							: !titleOk
								? 'Add a title before publishing.'
								: !contentOk
									? 'Add some content before publishing.'
									: '')}
				</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="I won't create a contact page, and I won't suggest this again."
				confirmLabel="Yes, dismiss"
				cancelLabel="Cancel"
				pending={pending === 'secondary'}
				onConfirm={confirmDismiss}
			/>
		</div>
	);
};

export default CreateContact;
