import { ArrowLeft, Check, ExternalLink, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import ConfirmDialog from '@/components/ui/confirm-dialog';
import FlavioIcon from '@/components/ui/flavio-icon';
import { getWordPressConfig, isAppPaused } from '@/api/client';
import { useInterventionResponse } from '@/features/interventions/useInterventionResponse';
import UpgradeLock from '@/features/interventions/detail/UpgradeLock';

/** Google Business Profile mark — storefront with striped awning and the "G". */
const GbpGlyph = ({ className }) => (
	<svg viewBox="0 0 512 512" className={className} aria-hidden="true">
		{/* Building */}
		<path
			fill="#4989F5"
			d="M64 232h384v220a12 12 0 0 1-12 12H76a12 12 0 0 1-12-12V232z"
		/>
		{/* Awning shadow cast on the building */}
		<path fill="#3A6FD6" opacity=".18" d="M64 232h236L64 460V232z" />
		{/* Awning — five scalloped panels, alternating tones */}
		<path fill="#6BA4F7" d="M40 78h86.4v118a43.2 43.2 0 0 1-86.4 0V78z" />
		<path
			fill="#3F73D7"
			d="M126.4 78h86.4v118a43.2 43.2 0 0 1-86.4 0V78z"
		/>
		<path
			fill="#6BA4F7"
			d="M212.8 78h86.4v118a43.2 43.2 0 0 1-86.4 0V78z"
		/>
		<path
			fill="#3F73D7"
			d="M299.2 78h86.4v118a43.2 43.2 0 0 1-86.4 0V78z"
		/>
		<path fill="#6BA4F7" d="M385.6 78H472v118a43.2 43.2 0 0 1-86.4 0V78z" />
		{/* Google "G" */}
		<g transform="translate(298 308) scale(2.6)" fill="#F1F3F4">
			<path d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
			<path d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
			<path d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
			<path d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-5.04 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
		</g>
	</svg>
);

/**
 * Detail for the `googconnection` intervention (the three Google setup handlers
 * deduped under one tag). One connect UI: explains why and links to the existing
 * connection flow (same URL as the header's "Manage connections").
 *
 * The scanner auto-resolves this once it detects the connections, but that can
 * lag. So we also give the user an explicit "I've already connected" action that
 * acknowledges the intervention (`status: 'acknowledge'`) and clears it from
 * their list right away.
 */
/**
 * Append `returnUrl=<current page>` to the `next_url` carried by the
 * authenticated connections URL, so the web flow can send the user back to this
 * exact intervention once they're done. `next_url` is a path (e.g.
 * `/growth/connections`); we encode the return URL into it and let
 * URLSearchParams handle the outer encoding.
 */
const withReturnUrl = (baseUrl) => {
	try {
		const url = new URL(baseUrl);
		const nextUrl = url.searchParams.get('next_url');
		if (!nextUrl) return baseUrl;
		const separator = nextUrl.includes('?') ? '&' : '?';
		const returnUrl = encodeURIComponent(window.location.href);
		url.searchParams.set('next_url', `${nextUrl}${separator}returnUrl=${returnUrl}`);
		return url.toString();
	} catch {
		return baseUrl;
	}
};

const GoogConnection = ({ interventionId, onBack, onResolved }) => {
	const config = getWordPressConfig();
	const connectionsUrl = config?.flavioAuthenticatedUrls?.connections;
	// Trial ended: the intervention can't be acted on, so its action buttons are
	// swapped for the single "unlock" upgrade CTA.
	const isPaused = isAppPaused();
	// The web flow sends the user back with `?connected=true` after they link
	// their account, so we highlight the confirm button in Flavio pink to nudge
	// them to acknowledge it.
	const justConnected =
		new URLSearchParams(window.location.search).get('connected') === 'true';

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

	if (resolved) {
		const skipped = resolved === 'secondary';
		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">
					{skipped ? 'No problem' : 'Got it'}
				</h1>
				<div className="max-w-md mx-auto">
					<p className="paragraph-regular text-muted-foreground mb-0!">
						{skipped
							? "I'll skip this for now. Without your Business Profile, your business may not appear in local search."
							: "Thanks. I'll check your Google Business Profile and pick things up from there."}
					</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="rounded-2xl border border-border overflow-hidden">
				{/* Main: explain why and link to the connection flow */}
				<div className="p-10 text-center">
					<span className="inline-flex items-center justify-center w-14 h-14 rounded-2xl border border-border bg-white shadow-sm mb-6">
						<GbpGlyph className="w-9 h-9" />
					</span>
					<h1 className="heading-h3 mt-0! leading-tight mb-3">
						Connect your Business Profile
					</h1>
					<div className="max-w-md mx-auto mb-8">
						<p className="paragraph-regular text-muted-foreground mb-0!">
							I'll open the Flavio web in a new tab, where you can
							connect your Google Business Profile. Nothing changes
							on your site until you're done.
						</p>
					</div>

					{isPaused ? (
						<UpgradeLock />
					) : (
						connectionsUrl && (
							<Button
								asChild
								size="lg"
								className="bg-foreground text-background! hover:bg-foreground/90"
							>
								<a
									href={withReturnUrl(connectionsUrl)}
									target="_blank"
									rel="noopener noreferrer"
								>
									Connect Business Profile
									<ExternalLink />
								</a>
							</Button>
						)
					)}
				</div>

				{/* Footer escape hatches. "I've already connected it"
				    acknowledges so the intervention clears now, without waiting
				    for the scanner to catch up. "Skip this for now" is layout
				    only — no handler wired yet. Hidden while paused: no actions
				    are available until the user upgrades. */}
				{!isPaused && (
					<div className="border-t border-border bg-muted/40 px-8 py-6 text-center">
						<p className="label-medium uppercase tracking-wide text-muted-foreground text-left my-0!">
							Already set up?
						</p>
						<div className="mt-4 flex flex-col sm:flex-row gap-3">
							<Button
								onClick={() =>
									run('primary', {
										status: 'acknowledge',
										userResponse: { choice: 'already_done' },
									})
								}
								disabled={!!pending || !!resolved}
								variant="secondary"
								size="lg"
								className={
									justConnected
										? 'flex-1 border border-magenta-500 bg-magenta-500 text-white hover:bg-magenta-600 hover:text-white'
										: 'flex-1 border border-neutral-300'
								}
							>
								{pending === 'primary' ? (
									<Loader2 className="animate-spin" />
								) : (
									<Check />
								)}
								I've already connected it
							</Button>
							<Button
								onClick={() =>
									run('secondary', { status: 'dismiss' })
								}
								disabled={!!pending || !!resolved}
								variant="outline"
								size="lg"
								className="flex-1 border-destructive/20 text-destructive/80 hover:bg-destructive/5 hover:text-destructive"
							>
								{pending === 'secondary' && (
									<Loader2 className="animate-spin" />
								)}
								Skip this for now
							</Button>
						</div>

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

			{!isPaused && (
				<div className="max-w-md mx-auto mt-4">
					<p className="small-regular text-muted-foreground text-center my-0!">
						Skipping won't connect your profile. Your business may
						not appear in local search.
					</p>
				</div>
			)}

			<ConfirmDialog
				open={confirmingDismiss}
				onOpenChange={(open) => {
					if (!pending && !open) cancelDismiss();
				}}
				title="Skip connecting your Business Profile?"
				description="I won't connect it, and your business may not appear in local search. I won't suggest this again."
				confirmLabel="Yes, skip"
				cancelLabel="Cancel"
				pending={pending === 'secondary'}
				onConfirm={confirmDismiss}
			/>
		</div>
	);
};

export default GoogConnection;
