import {
	ArrowLeft,
	Check,
	Loader2,
	Phone,
	Mail,
	MapPin,
	FileText,
	ExternalLink,
	RotateCcw,
	Sparkles,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import FlavioIcon from '@/components/ui/flavio-icon';
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 `checknap` / `request_nap` intervention (type selection,
 * phase 2 after the shared `contact` form).
 *
 * Flavio is about to inject a NAP block (Name, Address, Phone — plus email)
 * into the existing contact page. The block itself is a deterministic template
 * built by `buildNapHtmlBlock`, so nothing here is editable: we show the user
 * the exact literals that will land on the page and ask for approval.
 *
 * Contract metadata: `contact_path`, `wp_post_id`, `wp_post_type`, `builder`,
 * `proposed_phone?`, `proposed_email?`, `proposed_address?`,
 * `options:[apply, keep_current]`, `drift_detected?`.
 * userResponse: { choice:"apply" | "keep_current" }. Both submit as
 * `acknowledge` — no dismiss path here.
 *
 * Defensive on metadata: every field is read with a fallback. We render
 * `resolvePageRef` over a synthesized `{page_path: contact_path}` so the chip
 * uses the same component as the other text-proposal handlers.
 */
const CheckNap = ({
	intervention = {},
	interventionId,
	onBack,
	onResolved,
}) => {
	const m = intervention.metadata || {};
	const phone = m.proposed_phone || '';
	const email = m.proposed_email || '';
	const address = m.proposed_address || '';
	const driftDetected = m.drift_detected === true;

	// 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 { pageLabel, pageUrl } = resolvePageRef({ page_path: m.contact_path });

	const fields = [
		phone && { key: 'phone', icon: Phone, value: phone },
		email && { key: 'email', icon: Mail, value: email },
		address && { key: 'address', icon: MapPin, value: address, multiline: true },
	].filter(Boolean);

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

	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 these to your contact page shortly."
							: "No problem. I'll leave your contact page as it is."}
					</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 your business contact info to your contact page
				</h1>
				<div className="max-w-xl mx-auto mb-3">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						{driftDetected
							? "I noticed your contact page no longer shows the info I'd added. I can put it back below."
							: "Your contact page is missing the basics. I'll add them at the bottom so visitors (and Google) can find you."}
					</p>
				</div>
				{pageLabel &&
					(pageUrl ? (
						<a
							href={pageUrl}
							target="_blank"
							rel="noopener noreferrer"
							className="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 mb-8"
						>
							<FileText className="w-3.5 h-3.5" />
							{pageLabel}
							<ExternalLink className="w-3 h-3" />
						</a>
					) : (
						<div className="inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1 small-medium text-muted-foreground mb-8">
							<FileText className="w-3.5 h-3.5" />
							{pageLabel}
						</div>
					))}
			</div>

			{/* Page recreation: existing content placeholder + NAP block preview */}
			<div className="rounded-2xl border border-border overflow-hidden">
				<div className="px-5 py-3 bg-muted/30 border-b border-border flex items-center gap-2 small-medium text-muted-foreground">
					<FileText className="w-4 h-4" />
					Contact page preview
				</div>
				<div className="p-5">
					<p className="small-semibold uppercase tracking-wide text-muted-foreground my-0! mb-3!">
						Your existing content
					</p>
					<div className="space-y-2.5" aria-hidden="true">
						<div className="h-3 bg-muted/60 rounded w-full" />
						<div className="h-3 bg-muted/60 rounded w-5/6" />
						<div className="h-3 bg-muted/60 rounded w-4/6" />
					</div>
					<p className="small-regular italic text-muted-foreground/70 mt-2! mb-0!">
						Stays exactly as it is.
					</p>

					<div className="border-t border-dashed border-border my-5" />

					<div className="rounded-xl border border-magenta-200 bg-magenta-50 p-4">
						<p className="small-semibold uppercase tracking-wide text-magenta-600 my-0! mb-3!">
							What I'll add at the bottom
						</p>
						{fields.length > 0 ? (
							<div className="space-y-2.5">
								{fields.map((field) => {
									const Icon = field.icon;
									return (
										<div
											key={field.key}
											className={`flex gap-2.5 ${field.multiline ? 'items-start' : 'items-center'}`}
										>
											<Icon
												className={`w-4 h-4 text-magenta-600 shrink-0 ${field.multiline ? 'mt-1' : ''}`}
											/>
											<span className="text-foreground break-words">
												{field.value}
											</span>
										</div>
									);
								})}
							</div>
						) : (
							<p className="small-regular italic text-muted-foreground/70 my-0!">
								Nothing to add yet. I'll come back once I have your
								contact details.
							</p>
						)}
					</div>
				</div>
			</div>

			<div className="mt-4 flex items-start justify-center gap-2 small-regular text-muted-foreground">
				<Sparkles className="w-4 h-4 shrink-0 mt-0.5 text-magenta-500" />
				<span className="text-left max-w-xl">
					I'll inject these as a small block at the end of your contact
					page, leaving the rest of your content untouched.
				</span>
			</div>

			<div className="flex items-center justify-center gap-3 mt-8">
				{isPaused ? (
					<UpgradeLock />
				) : (
					<>
						<Button
							onClick={() =>
								run('primary', {
									status: 'acknowledge',
									userResponse: { choice: 'apply' },
								})
							}
							disabled={
								fields.length === 0 || !!pending || !!resolved
							}
							size="lg"
							className="bg-foreground text-background! hover:bg-foreground/90"
						>
							{pending === 'primary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<Check />
							)}
							Add to my contact page
						</Button>
						<Button
							onClick={() =>
								run('secondary', {
									status: 'acknowledge',
									userResponse: { choice: 'keep_current' },
								})
							}
							disabled={!!pending || !!resolved}
							size="lg"
							variant="outline"
						>
							{pending === 'secondary' ? (
								<Loader2 className="animate-spin" />
							) : (
								<RotateCcw />
							)}
							Keep current
						</Button>
					</>
				)}
			</div>

			{!isPaused && 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 changes until you choose.
			</p>
		</div>
	);
};

export default CheckNap;
