import { useState } from 'react';
import {
	AlertTriangle,
	ShieldCheck,
	Copy,
	Check,
	RefreshCw,
	UserRound,
	KeyRound,
	ServerCrash,
	Globe,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { getWordPressConfig } from '@/api/client';
import OnboardingLayout from '@/features/onboarding/OnboardingLayout';

/**
 * ConnectionBlocked
 *
 * Full-page gate shown when the connection with the site cannot be
 * established: the plugin tried to create/verify the Application Password on
 * this page load and failed for a known reason, or skipped the attempt
 * because the API reports a state that rotating cannot fix (unreachable).
 * Generalizes the old HttpsRequired screen (which is now a thin wrapper over
 * the no_https variant) with one guidance block per failure reason.
 *
 * Nothing is persisted here: "Check again" reloads the page, which re-runs
 * the whole connection attempt (User::maybe_send_application_password).
 */

/** A single numbered step in a "how to fix it" card. */
const Step = ({ n, children }) => (
	<div className="flex items-start gap-4">
		<span className="flex items-center justify-center w-7 h-7 rounded-full border border-border small-semibold text-muted-foreground shrink-0">
			{n}
		</span>
		<div className="min-w-0 pt-0.5">{children}</div>
	</div>
);

/** Copy-to-clipboard button for a ready-made message to the hosting support. */
const CopyMessageButton = ({ message }) => {
	const [copied, setCopied] = useState(false);

	const copyMessage = async () => {
		try {
			await navigator.clipboard.writeText(message);
			setCopied(true);
			setTimeout(() => setCopied(false), 1500);
		} catch {
			/* clipboard blocked; silent */
		}
	};

	return (
		<button
			type="button"
			onClick={copyMessage}
			className="inline-flex items-center gap-1.5 mt-2 small-semibold text-magenta-500 hover:text-magenta-600 transition-colors cursor-pointer"
		>
			{copied ? (
				<>
					<Check className="w-4 h-4" />
					Copied
				</>
			) : (
				<>
					<Copy className="w-4 h-4" />
					Copy a message for them
				</>
			)}
		</button>
	);
};

const RetryButton = ({ icon = <RefreshCw />, children = 'Check again' }) => (
	<div className="mt-10">
		<Button
			onClick={() => window.location.reload()}
			size="lg"
			className="bg-foreground text-background! hover:bg-foreground/90"
		>
			{icon}
			{children}
		</Button>
	</div>
);

/** Card with an icon header and free content. */
const Card = ({ title, children }) => (
	<div className="rounded-2xl border border-border p-6">
		<p className="small-semibold uppercase tracking-wide text-muted-foreground my-0! mb-5">
			{title}
		</p>
		<div className="space-y-5 mt-5">{children}</div>
	</div>
);

// ── Variants ─────────────────────────────────────────────────────

const NoHttps = ({ detail }) => {
	const { siteUrl } = getWordPressConfig() || {};
	const url = siteUrl || '';
	const [, protocol = '', domain = url] =
		url.match(/^(https?:\/\/)(.*)$/) || [];

	const isProxyCase = /proxy/i.test(detail || '');

	const message = `Hi, I'd like to enable a free SSL certificate (Let's Encrypt) for ${
		domain || 'my site'
	} so it loads securely over HTTPS. Most setups have a one-click option for this. Could you switch it on for me? Thanks!`;

	return (
		<OnboardingLayout
			title="First things first: let's get you on HTTPS."
			wide
		>
			<div className="mb-8">
				<p className="paragraph-regular text-foreground my-0!">
					I work directly on your live site, so before anything else
					it needs to be served securely over HTTPS. Right now it
					isn&apos;t. Once that&apos;s sorted, I can get started.
				</p>
			</div>

			<div className="grid md:grid-cols-2 gap-4">
				{/* YOUR SITE */}
				<div className="rounded-2xl border border-border p-6">
					<p className="small-semibold uppercase tracking-wide text-muted-foreground my-0!">
						Your site
					</p>
					<div className="flex items-center gap-3 mt-4">
						<span className="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-red-50 text-red-600 shrink-0">
							<AlertTriangle className="w-5 h-5" />
						</span>
						<span className="font-mono text-sm min-w-0 break-all">
							<span className="text-red-600 font-semibold">
								{protocol || 'http://'}
							</span>
							<span className="text-foreground">{domain}</span>
						</span>
						<span className="ml-auto inline-flex items-center gap-1.5 small-medium text-red-600 shrink-0">
							<span className="w-1.5 h-1.5 rounded-full bg-red-500" />
							Not secure
						</span>
					</div>
					<hr className="border-border my-4" />
					<p className="small-regular text-muted-foreground my-0!">
						{isProxyCase ? (
							<>
								If your site already loads over{' '}
								<span className="font-mono font-semibold text-foreground">
									https://
								</span>{' '}
								in your browser, your hosting is ending the
								secure connection at a proxy without telling
								WordPress. Ask them to pass the{' '}
								<span className="font-mono font-semibold text-foreground">
									X-Forwarded-Proto
								</span>{' '}
								header through.
							</>
						) : (
							<>
								Your site is being served over{' '}
								<span className="font-mono font-semibold text-foreground">
									http://
								</span>
								, without a certificate. Browsers show a
								&ldquo;Not secure&rdquo; warning to your
								visitors.
							</>
						)}
					</p>
				</div>

				{/* HOW TO SWITCH IT ON */}
				<Card title="How to switch it on">
					<Step n={1}>
						<p className="small-regular text-foreground my-0!">
							Contact your hosting provider.
						</p>
					</Step>
					<Step n={2}>
						<p className="small-regular text-foreground my-0!">
							Ask them to enable an SSL certificate (e.g.
							Let&apos;s Encrypt, it&apos;s free). Most hosts have
							a one-click option.
						</p>
						<CopyMessageButton message={message} />
					</Step>
					<Step n={3}>
						<p className="small-regular text-foreground my-0!">
							Come back and hit &ldquo;Check again&rdquo;.
							I&apos;ll take it from there.
						</p>
					</Step>
				</Card>
			</div>

			<RetryButton icon={<ShieldCheck />} />
		</OnboardingLayout>
	);
};

const AuthNotArriving = () => {
	const { siteUrl } = getWordPressConfig() || {};
	const domain = (siteUrl || '').replace(/^https?:\/\//, '') || 'my site';

	const message = `Hi, my WordPress site ${domain} is not receiving the Authorization header, so REST API calls with Application Passwords always fail with a 401 error. Could you make sure the header reaches PHP? On Apache with CGI/FastCGI this usually means adding this line to the .htaccess file: "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]" (or enabling CGIPassAuth). If the site is behind a proxy, please also pass the X-Forwarded-Proto header through. Thanks!`;

	return (
		<OnboardingLayout
			title="Your server is not delivering my credentials to WordPress."
			wide
		>
			<div className="mb-8">
				<p className="paragraph-regular text-foreground my-0!">
					I created my access credentials on your site just fine, but
					when I use them your server drops them before they reach
					WordPress. This is a server configuration issue, and
					creating new credentials will not fix it. Here are the usual
					culprits, in order.
				</p>
			</div>

			<Card title="How to fix it">
				<Step n={1}>
					<p className="small-regular text-foreground my-0!">
						Check your security plugins first. Some of them (for
						example Wordfence Login Security) disable Application
						Passwords by default. Look for that option and enable
						them.
					</p>
				</Step>
				<Step n={2}>
					<p className="small-regular text-foreground my-0!">
						If that is not it, your hosting is likely stripping the{' '}
						<span className="font-mono font-semibold">
							Authorization
						</span>{' '}
						header. Contact them and share the details; it is a one
						line fix on their side.
					</p>
					<CopyMessageButton message={message} />
				</Step>
				<Step n={3}>
					<p className="small-regular text-foreground my-0!">
						Once it is sorted, come back and hit &ldquo;Check
						again&rdquo;. No need to reconnect anything: your
						credentials are already in place.
					</p>
				</Step>
			</Card>

			<RetryButton icon={<KeyRound />} />
		</OnboardingLayout>
	);
};

const AppPasswordsDisabled = () => {
	const { siteUrl } = getWordPressConfig() || {};
	const domain = (siteUrl || '').replace(/^https?:\/\//, '') || 'my site';

	const message = `Hi, I need Application Passwords enabled on my WordPress site ${domain} (they are a core WordPress feature since version 5.6). They are currently disabled, probably by a security setting or plugin. Could you enable them? Thanks!`;

	return (
		<OnboardingLayout
			title="Application Passwords are disabled on your site."
			wide
		>
			<div className="mb-8">
				<p className="paragraph-regular text-foreground my-0!">
					I connect to your site using WordPress Application
					Passwords, a built-in WordPress feature. Something on your
					site is switching them off, so I cannot create my access
					credentials.
				</p>
			</div>

			<Card title="How to fix it">
				<Step n={1}>
					<p className="small-regular text-foreground my-0!">
						Review your security plugins (for example Wordfence
						Login Security disables Application Passwords by
						default) and enable them there.
					</p>
				</Step>
				<Step n={2}>
					<p className="small-regular text-foreground my-0!">
						If you cannot find the option, ask your hosting provider
						or developer.
					</p>
					<CopyMessageButton message={message} />
				</Step>
				<Step n={3}>
					<p className="small-regular text-foreground my-0!">
						Then come back and hit &ldquo;Check again&rdquo;.
					</p>
				</Step>
			</Card>

			<RetryButton icon={<KeyRound />} />
		</OnboardingLayout>
	);
};

const InsufficientPermissions = () => (
	<OnboardingLayout title="An administrator needs to finish this step." wide>
		<div className="mb-8">
			<p className="paragraph-regular text-foreground my-0!">
				Connecting me to your site requires a WordPress administrator
				account, and the current user does not have those permissions.
				Ask an administrator of this site to open Flavio from their
				account; the connection will complete automatically.
			</p>
		</div>

		<RetryButton icon={<UserRound />} />
	</OnboardingLayout>
);

const Unreachable = () => {
	const { siteUrl } = getWordPressConfig() || {};
	const domain = (siteUrl || '').replace(/^https?:\/\//, '') || 'my site';

	const message = `Hi, automated requests to my WordPress site ${domain} are being blocked before they reach WordPress, most likely by an anti-bot or browser-verification challenge on the server. I need external services to be able to reach the WordPress REST API (for example ${domain}/index.php?rest_route=/). Could you disable that challenge for REST API requests, or whitelist them? Thanks!`;

	return (
		<OnboardingLayout
			title="Your hosting is blocking my access to your site."
			wide
		>
			<div className="mb-8">
				<p className="paragraph-regular text-foreground my-0!">
					My credentials for your site are in place, but every request
					I make from the outside gets intercepted before it reaches
					WordPress, usually by an anti-bot protection at your
					hosting. Until that block is lifted I cannot see or improve
					anything on your site, so I have paused my work.
					Reconnecting will not help; this needs a change on the
					server.
				</p>
			</div>

			<Card title="How to fix it">
				<Step n={1}>
					<p className="small-regular text-foreground my-0!">
						Contact your hosting provider and ask them to let
						external services reach the WordPress REST API. Some
						free hosting plans apply an anti-bot challenge to all
						traffic and do not allow turning it off; in that case
						you would need a plan or provider without that
						restriction.
					</p>
					<CopyMessageButton message={message} />
				</Step>
				<Step n={2}>
					<p className="small-regular text-foreground my-0!">
						If you use a security service or firewall (for example
						Cloudflare), check that its bot protection is not
						challenging requests to{' '}
						<span className="font-mono font-semibold">
							/wp-json/
						</span>{' '}
						or{' '}
						<span className="font-mono font-semibold">
							?rest_route=
						</span>
						.
					</p>
				</Step>
				<Step n={3}>
					<p className="small-regular text-foreground my-0!">
						Once it is sorted, I will detect it and resume my work
						automatically within a few hours. No need to reconnect
						anything: your credentials are already in place.
					</p>
				</Step>
			</Card>

			<RetryButton icon={<Globe />} />
		</OnboardingLayout>
	);
};

const TemporaryFailure = () => (
	<OnboardingLayout title="I could not finish connecting to your site." wide>
		<div className="mb-8">
			<p className="paragraph-regular text-foreground my-0!">
				Something went wrong while setting up my access credentials.
				This is usually temporary: a hiccup on your server or on our
				side. Give it a moment and try again.
			</p>
		</div>

		<RetryButton icon={<ServerCrash />}>Try again</RetryButton>
	</OnboardingLayout>
);

// ── Entry point ──────────────────────────────────────────────────

const ConnectionBlocked = ({ reason, detail }) => {
	switch (reason) {
		case 'no_https':
			return <NoHttps detail={detail} />;
		case 'auth_not_arriving':
			return <AuthNotArriving />;
		case 'app_passwords_disabled':
			return <AppPasswordsDisabled />;
		case 'insufficient_permissions':
			return <InsufficientPermissions />;
		case 'unreachable':
			return <Unreachable />;
		default:
			// create_failed | save_failed | unknown
			return <TemporaryFailure />;
	}
};

export default ConnectionBlocked;
