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

const LOADING_TASKS = [
	{ id: 1, label: 'Exploring your website', delay: 800 },
	{ id: 2, label: 'Understanding what you offer', delay: 2000 },
	{ id: 3, label: 'Checking your local presence', delay: 3500 },
	{ id: 4, label: 'Pinning down your location', delay: 5000 },
];

const POLL_INTERVAL = 3000;

/**
 * LoadingProfile Step
 *
 * 1. Saves the goal to backend (POST /business-info)
 * 2. Triggers profile inference (POST /onboarding/goal)
 * 3. Polls for result (GET /onboarding/goal) until completed or failed
 * 4. Checklist loops until API responds, then completes
 */
const LoadingProfile = ({ onNext, data, onConnectionBlocked }) => {
	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();

	// If goal already exists in siteInfo, POSTs were already done — just poll
	const isResuming = !!window.flavioData?.siteInfo?.goal;

	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.onboardingGoal);

				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) ||
							'Profile inference failed.'
					);
				}
			} catch (err) {
				if (stoppedRef.current) return;
				cleanup();
				if (isSiteUnreachableError(err)) {
					onConnectionBlocked?.();
					return;
				}
				logError(err, {
					action: 'poll_goal',
					component: 'LoadingProfile',
				});
				setApiError(
					getErrorMessage(
						err,
						'Failed to get profile results. Please try again.'
					)
				);
			}
		}, POLL_INTERVAL);
	}, [endpoints.onboardingGoal, cleanup, onConnectionBlocked]);

	const triggerAndPoll = useCallback(async () => {
		cleanup();
		setApiError(null);
		setApiResult(null);
		setIsRetrying(true);

		try {
			// Save goal + trigger inference (skip if resuming — already done)
			if (!isResuming) {
				await post(endpoints.businessInfo, { goal: data.goal });
				await post(endpoints.onboardingGoal, { goal: data.goal });
			}

			pollForResult();
		} catch (err) {
			logError(err, {
				action: 'trigger_goal_inference',
				component: 'LoadingProfile',
			});
			setApiError(
				getErrorMessage(
					err,
					'Failed to analyze your website. Please try again.'
				)
			);
		} finally {
			setIsRetrying(false);
		}
	}, [endpoints, data.goal, cleanup, pollForResult, isResuming]);

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

	const handleComplete = () => {
		onNext({ businessProfileResponse: apiResult });
	};

	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={triggerAndPoll}
							disabled={isRetrying}
						>
							{isRetrying ? 'Retrying...' : 'Try Again'}
						</Button>
					</div>
				</div>
			</div>
		);
	}

	return (
		<ProgressChecklist
			title="Getting to know your business..."
			subtitle="I'm taking a look at your website to understand what you do and where you operate. This helps me focus on what matters most."
			tasks={LOADING_TASKS}
			canComplete={!!apiResult}
			onComplete={handleComplete}
		/>
	);
};

export default LoadingProfile;
