import { ExternalLink, Unplug } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { getWordPressConfig } from '@/api/client';
import { withReturnUrl } from '@/utils/urlBuilder';
import { getGoogleConnectionState } from '@/features/connection/googleConnectionState';

/**
 * GoogleConnectionNotice
 *
 * Highlighted dashboard notice shown when Flavio lost access to the user's
 * Google connection (token revoked, permission lost, or disconnected from the
 * web). It is separate from the "Needs your attention" list on purpose: this
 * is not one more question, it is "Flavio needs you" with a single action.
 *
 * Driven by `planInfo.google_connection` (goo `plan-info`), injected once per
 * page load. A site that never connected Google has `status: null` and sees
 * nothing here (the connect intervention covers that case).
 */

const SERVICE_COPY = {
	business_profile: {
		name: 'Google Business Profile',
		loss: 'keep your Business Profile up to date so you show up on Search and Maps',
	},
	search_console: {
		name: 'Search Console',
		loss: 'see how your pages rank on Google',
	},
	analytics: {
		name: 'Google Analytics',
		loss: 'measure the traffic your website gets',
	},
};

const REASON_HINT = {
	token_revoked: 'It looks like access was removed from your Google account.',
	scope_revoked:
		'It looks like a permission was left out the last time you connected.',
	permission_denied: 'Google no longer lets me manage it with this account.',
	disconnected: 'It was disconnected from your Flavio settings.',
	missing_credentials: 'The connection details are incomplete.',
};

const joinNames = (names) => {
	if (names.length <= 1) return names[0] ?? '';
	return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
};

const GoogleConnectionNotice = () => {
	const config = getWordPressConfig();
	const state = getGoogleConnectionState();
	if (!state) return null;

	const connectionsUrl = config?.flavioAuthenticatedUrls?.connections;
	const affected = (state.affected_services || []).filter(
		(service) => SERVICE_COPY[service]
	);
	const known = affected.length > 0;
	const onlyBusiness =
		affected.length === 1 && affected[0] === 'business_profile';

	const title = onlyBusiness
		? 'I lost access to your Google Business Profile'
		: 'I lost access to your Google account';
	const lost = known
		? `Until you reconnect I can't ${joinNames(affected.map((s) => SERVICE_COPY[s].loss))}.`
		: "Until you reconnect I can't keep working on your Google presence.";
	const hint = REASON_HINT[state.reason] ?? '';
	const cta = onlyBusiness
		? 'Reconnect Business Profile'
		: 'Reconnect Google';

	return (
		<section className="mb-10" data-testid="google-connection-notice">
			<div className="rounded-xl bg-red-50/60 border border-red-200 px-6 py-5">
				<div className="flex items-center gap-4">
					<div
						className="w-10 h-10 rounded-lg flex items-center justify-center shrink-0"
						style={{ backgroundColor: 'rgba(239, 68, 68, 0.12)' }}
					>
						<Unplug className="w-5 h-5 text-red-500" />
					</div>
					<div className="flex-1 min-w-0">
						<p className="paragraph-semibold text-foreground m-0!">
							{title}
						</p>
						<p className="small-regular text-muted-foreground mt-0.5 m-0!">
							{hint ? `${hint} ` : ''}
							{lost}
						</p>
					</div>
					{connectionsUrl && (
						<Button
							asChild
							size="lg"
							className="bg-foreground text-background! hover:bg-foreground/90 shrink-0"
						>
							<a
								href={withReturnUrl(connectionsUrl)}
								target="_blank"
								rel="noopener noreferrer"
							>
								{cta}
								<ExternalLink />
							</a>
						</Button>
					)}
				</div>
			</div>
		</section>
	);
};

export default GoogleConnectionNotice;
