import { useState, useEffect, useRef, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { ProgressChecklist } from '@/components/ui/progress-checklist';
import { get, getWordPressConfig } from '@/api/client';
import { logError } from '@/errors/logger';
import { getErrorMessage } from '@/utils/errorMessages';
import { isSiteUnreachableError } from '@/utils/executorConnection';

const NEW_TAGLINE_TASKS = [
	{ id: 1, label: 'Saving your new tagline', delay: 800 },
	{ id: 2, label: 'Updating your homepage', delay: 2000 },
	{ id: 3, label: 'Setting up your plan', delay: 3500 },
	{ id: 4, label: 'Wrapping up', delay: 5000 },
];

const KEEP_TAGLINE_TASKS = [
	{ id: 1, label: 'Confirming your tagline', delay: 800 },
	{ id: 2, label: 'Moving on to the next task', delay: 2000 },
	{ id: 3, label: 'Preparing your next steps', delay: 3500 },
	{ id: 4, label: 'Wrapping up', delay: 5000 },
];

const POLL_INTERVAL = 3000;

/**
 * Complete Step
 *
 * The POST to /onboarding/tagline was already sent by TaglineSelection.
 * This step polls GET /onboarding/tagline until the tagline is applied.
 */
const Complete = ({ onNext, data, onConnectionBlocked }) => {
	const keptCurrent = data?.selectedTaglineType === 'current';
	const [apiResult, setApiResult] = useState(null);
	const [apiError, setApiError] = useState(null);
	const [isRetrying, setIsRetrying] = useState(false);
	const stoppedRef = useRef(false);
	const intervalRef = useRef(null);

	const { endpoints } = getWordPressConfig();

	const cleanup = useCallback(() => {
		stoppedRef.current = true;
		if (intervalRef.current) {
			clearInterval(intervalRef.current);
			intervalRef.current = null;
		}
	}, []);

	const pollForResult = useCallback(() => {
		stoppedRef.current = false;

		intervalRef.current = setInterval(async () => {
			if (stoppedRef.current) return;

			try {
				const response = await get(endpoints.onboardingTagline);

				if (stoppedRef.current) return;

				if (response.status === 'completed') {
					cleanup();
					setApiResult(response.result);
				} else if (response.status === 'failed') {
					cleanup();
					if (isSiteUnreachableError(response.error)) {
						onConnectionBlocked?.();
						return;
					}
					setApiError(
						(typeof response.error === 'string' &&
							response.error) ||
							'Failed to apply tagline.'
					);
				}
			} catch (err) {
				if (stoppedRef.current) return;
				cleanup();
				if (isSiteUnreachableError(err)) {
					onConnectionBlocked?.();
					return;
				}
				logError(err, {
					action: 'poll_tagline',
					component: 'Complete',
				});
				setApiError(
					getErrorMessage(
						err,
						'Failed to apply your tagline. Please try again.'
					)
				);
			}
		}, POLL_INTERVAL);
	}, [endpoints.onboardingTagline, cleanup, onConnectionBlocked]);

	const startPolling = useCallback(() => {
		cleanup();
		setApiError(null);
		setApiResult(null);
		setIsRetrying(false);
		pollForResult();
	}, [cleanup, pollForResult]);

	useEffect(() => {
		startPolling();
		return cleanup;
	}, []); // eslint-disable-line react-hooks/exhaustive-deps

	const handleComplete = () => {
		onNext();
	};

	const handleRetry = () => {
		setIsRetrying(true);
		startPolling();
	};

	if (apiError) {
		return (
			<div className="flex flex-col items-center justify-center py-16 px-6">
				<div className="w-full max-w-2xl">
					<div className="p-6 bg-destructive/10 border border-destructive/20 rounded-lg text-center">
						<p className="paragraph-regular text-destructive mb-4">
							{apiError}
						</p>
						<Button
							onClick={handleRetry}
							disabled={isRetrying}
						>
							{isRetrying ? 'Retrying...' : 'Try Again'}
						</Button>
					</div>
				</div>
			</div>
		);
	}

	return (
		<ProgressChecklist
			title={keptCurrent ? 'Got it, keeping your tagline...' : 'Applying your new tagline...'}
			subtitle={
				keptCurrent
					? <>I'm confirming your choice and getting everything ready for what's next.</>
					: <>I'm updating your tagline right now. Once that's done, I'll set up your plan so you can see what's next.</>
			}
			tasks={keptCurrent ? KEEP_TAGLINE_TASKS : NEW_TAGLINE_TASKS}
			canComplete={!!apiResult}
			onComplete={handleComplete}
		/>
	);
};

export default Complete;
