import { useState } from 'react';
import { T, useTranslate } from '@tolgee/react';
import { ChevronRight, ShieldCheck, LockKeyhole } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import OnboardingLayout from '@/features/onboarding/OnboardingLayout';
import ConnectionBlocked from '@/features/connection/ConnectionBlocked';
import { post, getWordPressConfig } from '@/api/client';
import { logError } from '@/errors/logger';
import { getErrorMessage } from '@/utils/errorMessages';

/** One of the two reassurance cards under the description. */
const Fact = ({ icon, title, children }) => {
	const Icon = icon;
	return (
		<div className="rounded-2xl bg-neutral-100 p-6">
			<div className="flex items-start gap-3">
				<Icon
					size={20}
					strokeWidth={2}
					className="text-green-600 shrink-0 mt-0.5"
					aria-hidden="true"
				/>
				<div className="min-w-0">
					<p className="paragraph-bold text-foreground my-0!">
						{title}
					</p>
					<p className="small-regular text-muted-foreground my-0! mt-1">
						{children}
					</p>
				</div>
			</div>
		</div>
	);
};

/**
 * ConnectSite
 *
 * Explicit consent screen for the WordPress Application Password. The plugin
 * never creates that credential on its own: it only does so when the user hits
 * "Accept and continue" here (POST /flavio/v1/connection). Used as the
 * onboarding step right before the tagline (steps/Connect) and as the
 * post-onboarding gate in App.jsx when the connection has to be re-established
 * (credential revoked, security plugin, ...).
 *
 * Only one way forward: there is no "skip". If the attempt fails for a known
 * reason (no HTTPS, Application Passwords disabled, ...) the per-cause guidance
 * from ConnectionBlocked takes over; its "Check again" reloads the page, which
 * lands back here while the connection is still needed.
 *
 * @param {Object} connection - Load-time state from window.flavioData
 *   ({needed, attempted, connected, reason, detail}). A `reason` at load time
 *   means the preflight already failed, so the guidance is shown straight away
 *   instead of asking permission for something that cannot work.
 * @param {Function} onConnected - Called once the credential is in place.
 * @param {boolean} [reconnect=false] - Re-establishing a lost connection
 *   (post-onboarding) rather than connecting for the first time.
 */
const ConnectSite = ({ connection, onConnected, reconnect = false }) => {
	const { t } = useTranslate('plugin');
	const { endpoints, supportUrls } = getWordPressConfig();
	const [state, setState] = useState(connection || {});
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState(null);

	if (state.reason) {
		return (
			<ConnectionBlocked reason={state.reason} detail={state.detail} />
		);
	}

	const handleAccept = async () => {
		if (isSubmitting) return;
		setIsSubmitting(true);
		setError(null);

		try {
			const response = await post(endpoints.connection);
			const next = response?.connection || {};

			if (next.connected) {
				// Keep the button busy: the parent advances or reloads.
				onConnected?.();
				return;
			}

			// Known cause (or an unknown one): hand over to the guidance.
			setState({ ...next, reason: next.reason || 'unknown' });
		} catch (err) {
			logError(err, {
				action: 'authorize_application_password',
				component: 'ConnectSite',
			});
			setError(
				getErrorMessage(
					err,
					'I could not set up my access to your site. Please try again.'
				)
			);
			setIsSubmitting(false);
		}
	};

	const title = reconnect
		? t(
				'connection.consent.titleReconnect',
				'One permission before Flavio gets back to work'
			)
		: t(
				'connection.consent.title',
				'One permission before Flavio gets to work'
			);

	return (
		<OnboardingLayout title={title}>
			<div className="mb-8">
				{/* Two static <T> elements (not one with a conditional keyName):
				    the Tolgee extractor cannot see dynamic keys. */}
				<p className="paragraph-regular text-foreground my-0!">
					{reconnect ? (
						<T
							keyName="connection.consent.descriptionReconnect"
							defaultValue="Flavio's access to your website stopped working, so it needs a new WordPress <em>Application Password</em> to keep editing content on your website: titles, descriptions, image text and pages."
							params={{
								em: (
									<span className="text-magenta-500 font-semibold" />
								),
							}}
						/>
					) : (
						<T
							keyName="connection.consent.description"
							defaultValue="Flavio will create a WordPress <em>Application Password</em> so it can edit content on your website: titles, descriptions, image text and pages."
							params={{
								em: (
									<span className="text-magenta-500 font-semibold" />
								),
							}}
						/>
					)}
				</p>
			</div>

			<div className="grid md:grid-cols-2 gap-4 mb-16">
				<Fact
					icon={ShieldCheck}
					title={t(
						'connection.consent.notLogin.title',
						'Not your login'
					)}
				>
					{t(
						'connection.consent.notLogin.text',
						'Separate from your password. Cannot sign in to your admin.'
					)}
				</Fact>
				<Fact
					icon={LockKeyhole}
					title={t(
						'connection.consent.revocable.title',
						'Revocable anytime'
					)}
				>
					{t(
						'connection.consent.revocable.text',
						'Listed in Users › Profile. Revoke it and Flavio stops.'
					)}
				</Fact>
			</div>

			{/* admin-overrides.css resets every link inside #flavio (color inherit,
			    no underline, both !important), hence the important variants. */}
			<div className="mb-10">
				<p className="small-regular text-muted-foreground my-0!">
					<T
						keyName="connection.consent.learnMore"
						defaultValue="Want the full picture? <link>Read how Flavio uses Application Passwords</link> in the Support Center."
						params={{
							link: (
								<a
									href={supportUrls?.applicationPasswords}
									target="_blank"
									rel="noreferrer"
									className="text-magenta-500! underline! underline-offset-4 hover:text-magenta-600! transition-colors"
								/>
							),
						}}
					/>
				</p>
			</div>

			{error && (
				<div className="mb-6 p-4 bg-destructive/10 border border-destructive/20 rounded-lg">
					<p className="small-regular text-destructive my-0!">
						<strong className="font-semibold">Error:</strong>{' '}
						{error}
					</p>
				</div>
			)}

			<Button
				onClick={handleAccept}
				disabled={isSubmitting}
				size="lg"
				className="bg-foreground text-background! hover:bg-foreground/90"
			>
				{isSubmitting ? (
					<>
						<Spinner className="size-4" />
						{t(
							'connection.consent.working',
							'Setting up access...'
						)}
					</>
				) : (
					<>
						{t('connection.consent.accept', 'Accept and continue')}
						<ChevronRight />
					</>
				)}
			</Button>
		</OnboardingLayout>
	);
};

export default ConnectSite;
