import {
	CirclePause,
	ChevronRight,
	CircleCheck,
	Clock,
	BarChart3,
	TriangleAlert,
	Lock,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { getWordPressConfig, findCTA } from '@/api/client';
import { buildCTAUrl } from '@/utils/urlBuilder';
import useAreas from '@/hooks/useAreas';
import useInterventions from '@/hooks/useInterventions';
import usePageView from '@/hooks/analytics/usePageView';
import useTrackOnMount from '@/hooks/analytics/useTrackOnMount';
import useAnalytics from '@/hooks/analytics/useAnalytics';
import { EVENTS } from '@/lib/events';
import DetailRow from '@/features/timeline/DetailRow';

// Stagger delays in ms — irregular spacing so it feels organic, not mechanical
const STAGGER_DELAYS = [0, 70, 30, 110, 50, 80, 60];

// Refetch dashboard data on this cadence so progress / current area / new
// interventions stay live without a page reload (matches the header badge).
const POLL_INTERVAL_MS = 20000;

// Frozen progress shown while paused (the live value is time-based and would
// otherwise keep advancing, contradicting the "on hold" state).
const PAUSED_PROGRESS = 7;

/**
 * Wrapper that applies stagger animation to each dashboard section.
 */
const AnimatedSection = ({ index, transition, children }) => {
	const isExiting = transition === 'dashboard-exit';
	const isEntering = transition === 'dashboard-enter';

	if (!isExiting && !isEntering) return children;

	const animationName = isExiting
		? 'animate-stagger-out-left'
		: 'animate-stagger-in-left';

	return (
		<div
			className={animationName}
			style={{ animationDelay: `${STAGGER_DELAYS[index] || 0}ms` }}
		>
			{children}
		</div>
	);
};

/**
 * DashboardPage Component
 *
 * Main dashboard showing the current state of Flavio's work.
 * Fetches Focus Areas from the backend via useAreas hook.
 * Resolves display data (titles, icons, colors) from a static local map using the FA key.
 *
 * Three states share the same layout, differing only per-section:
 *   - working: Flavio is actively running a Focus Area.
 *   - blocked: the current FA has a blocking interaction (Flavio waits on the user).
 *   - paused:  the trial ended (an `app-upgrade` CTA is present). Everything is on
 *              hold until the user upgrades; we swap copy, freeze the progress bar,
 *              lock the next FA, and surface the upgrade action.
 */
const DashboardPage = ({ onTimelineClick, transition, onOpenIntervention }) => {
	usePageView('dashboard');
	useTrackOnMount(EVENTS.CURRENT_WORK_VIEWED);
	const { track } = useAnalytics();

	const config = getWordPressConfig();
	const {
		loading,
		currentArea,
		currentProgress,
		nextArea,
		recentImprovement,
		hasAnalytics,
		interaction,
	} = useAreas({ pollInterval: POLL_INTERVAL_MS });
	// "Flavio needs your help" card priority:
	//   1. Any blocking intervention from /interventions (urgent, amber).
	//   2. Otherwise, the current area's attached interaction (non-blocking, magenta).
	// Both come from /interventions (the area exposes only an id pointer), so we
	// look the area's interaction up by id in the resolved items list.
	const { items: interventions, blocking: blockingIntervention } =
		useInterventions({ pollInterval: POLL_INTERVAL_MS });
	const areaIntervention =
		!blockingIntervention && interaction?.id
			? interventions.find((i) => i.id === interaction.id) || null
			: null;
	const helpIntervention = blockingIntervention || areaIntervention;

	// When the trial has ended the backend exposes an `app-upgrade` CTA, which
	// flips the whole dashboard into its "paused" variant.
	const upgradeCTA = findCTA('app-upgrade');

	if (loading) {
		return (
			<main className="flex-1 overflow-y-auto">
				<div className="max-w-4xl mx-auto px-8 pt-10 pb-24">
					<div className="flex items-center gap-4">
						<div className="w-12 h-12 rounded-full bg-neutral-100 animate-pulse" />
						<div className="h-8 w-64 bg-neutral-100 rounded animate-pulse" />
					</div>
				</div>
			</main>
		);
	}

	// State flags drive the per-section variants below.
	const isPaused = !!upgradeCTA;
	const isBlocked = !isPaused && interaction?.blocking;
	const isWorking = !isPaused && !isBlocked;
	// Both paused and blocked freeze the progress bar (neutral, no live advance).
	const isFrozen = isPaused || isBlocked;
	const upgradeUrl = isPaused ? buildCTAUrl(upgradeCTA) : null;
	// While paused the live calculation keeps creeping up (it's time-based), which
	// looks wrong for a frozen state, so we pin the displayed progress to a fixed
	// value. The real currentProgress is still used for the working state.
	const displayProgress = isPaused ? PAUSED_PROGRESS : currentProgress;

	const recentFA = recentImprovement || {
		title: 'Getting to know your business',
		description:
			'Profiled your business, identified your target customer, and determined your local presence needs.',
	};

	return (
		<main className="flex-1 overflow-y-auto">
			<div className="max-w-4xl mx-auto px-8 pt-10 pb-24">
				{/* ── Title ── */}
				<AnimatedSection index={1} transition={transition}>
					<header
						className={`flex items-center gap-4 ${isPaused ? 'mb-3' : 'mb-10'}`}
					>
						<img
							src={`${config.pluginUrl}js/public/onboarding.svg`}
							alt="Flavio"
							className={`w-[48px] h-[48px] shrink-0 ${isPaused ? 'grayscale opacity-50' : ''}`}
							width="48"
							height="48"
						/>
						<h1 className="heading-h2">
							{isPaused
								? 'Flavio is paused'
								: 'Flavio is improving your website'}
						</h1>
					</header>
					{isPaused && (
						<p className="paragraph-regular text-muted-foreground mt-0! mb-10">
							Your trial has ended. Upgrade to keep Flavio
							scanning, fixing, and improving your website.
						</p>
					)}
				</AnimatedSection>

				{/* ── Analytics Banner (only when performance-insights is active) ── */}
				{!isPaused && hasAnalytics && (
					<AnimatedSection index={2} transition={transition}>
						<section className="mb-6">
							<div className="rounded-lg bg-blue-50 border border-blue-100 px-5 py-3 flex items-center justify-between">
								<div className="flex items-center gap-2.5">
									<BarChart3 className="w-4.5 h-4.5 text-blue-600" />
									<span className="text-sm text-foreground">
										<strong>Your numbers are in.</strong>{' '}
										See how your site is doing
									</span>
								</div>
								<button
									type="button"
									onClick={() => {
										track(EVENTS.MONTHLY_REPORT_OPENED, {
											source: 'dashboard_banner',
										});
										onTimelineClick('site-status');
									}}
									className="inline-flex items-center gap-1 small-semibold text-blue-600 hover:text-blue-700 transition-colors cursor-pointer"
								>
									See your results
									<ChevronRight className="w-4 h-4" />
								</button>
							</div>
						</section>
					</AnimatedSection>
				)}

				{/* ── Status box: working / blocked / paused ── */}
				{(currentArea || isPaused) && (
					<AnimatedSection index={2} transition={transition}>
						<section className="mb-10">
							<div className="rounded-lg border border-border shadow-sm bg-card p-6">
								{/* Badge */}
								<div className="mb-3">
									{isWorking ? (
										<span className="inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-semibold rounded-full bg-magenta-100 text-magenta-700">
											<span className="relative flex h-2 w-2">
												<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-magenta-500 opacity-75" />
												<span className="relative inline-flex rounded-full h-2 w-2 bg-magenta-500" />
											</span>
											Working
										</span>
									) : (
										<span
											className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-semibold rounded-full ${
												isPaused
													? 'bg-neutral-100 text-neutral-600'
													: 'bg-amber-100 text-amber-700'
											}`}
										>
											<CirclePause className="w-3 h-3" />
											Paused
										</span>
									)}
								</div>

								{/* Title */}
								<h2 className="heading-h3 text-foreground mb-4">
									{isPaused
										? 'Your website improvements are on hold'
										: currentArea.title}
								</h2>

								{/* Progress bar */}
								<div
									className={`flex items-center gap-3 ${isPaused ? 'mb-2' : 'mb-5'}`}
								>
									<div className="flex-1 h-2 rounded-full bg-neutral-100 overflow-hidden">
										<div
											className={`h-full rounded-full transition-all duration-700 ${
												isFrozen
													? 'bg-neutral-300'
													: 'bg-gradient-to-r from-magenta-500 to-magenta-400'
											}`}
											style={{
												width: `${displayProgress}%`,
											}}
										/>
									</div>
									<span className="small-semibold text-foreground tabular-nums shrink-0">
										{displayProgress}%
									</span>
								</div>
								{isPaused && currentArea && (
									<p className="small-regular text-muted-foreground m-0!">
										Stopped at {displayProgress}% ·{' '}
										{currentArea.title}
									</p>
								)}

								{/* Flavio message */}
								<div
									className={`rounded-lg bg-neutral-50 border border-neutral-100 p-4 ${isPaused ? 'mt-5' : ''}`}
								>
									<div className="flex items-start gap-3">
										<img
											src={`${config.pluginUrl}js/public/onboarding.svg`}
											alt=""
											className={`w-6 h-6 shrink-0 ${isWorking ? 'animate-spin' : ''} ${isPaused ? 'grayscale opacity-50' : ''}`}
											style={
												isWorking
													? {
															animationDuration:
																'3s',
														}
													: undefined
											}
											width="24"
											height="24"
										/>
										<p className="paragraph-regular text-foreground leading-relaxed m-0!">
											{isPaused
												? 'Flavio saved your progress. Upgrade to keep scanning, fixing, and improving your website automatically.'
												: currentArea.reason}
										</p>
									</div>
								</div>

								{/* Paused actions */}
								{isPaused && (
									<div className="flex flex-wrap items-center gap-3 mt-5">
										<Button
											asChild
											size="lg"
											className="bg-magenta-500 hover:bg-magenta-600"
										>
											<a
												href={upgradeUrl}
												target="_blank"
												rel="noopener noreferrer"
												className="!text-white"
											>
												Upgrade to unlock Flavio
											</a>
										</Button>
										<Button
											size="lg"
											variant="outline"
											onClick={() => onTimelineClick()}
										>
											View past improvements
										</Button>
									</div>
								)}
							</div>
						</section>
					</AnimatedSection>
				)}

				{/* ── Help card: any intervention that needs the user (hidden while paused) ── */}
				{!isPaused && helpIntervention && (
					<AnimatedSection index={3} transition={transition}>
						<section className="mb-10">
							<div className="rounded-xl bg-amber-50/50 border border-amber-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(245, 158, 11, 0.15)',
										}}
									>
										<TriangleAlert className="w-5 h-5 text-amber-500" />
									</div>
									<div className="flex-1 min-w-0">
										<p className="paragraph-semibold text-foreground m-0!">
											{helpIntervention.title}
										</p>
										{helpIntervention.description && (
											<p className="small-regular text-muted-foreground mt-0.5 m-0!">
												{helpIntervention.description}
											</p>
										)}
									</div>
									<Button
										size="lg"
										className="bg-foreground text-background hover:bg-foreground/90 shrink-0"
										onClick={() =>
											onOpenIntervention?.(
												helpIntervention.id
											)
										}
									>
										{helpIntervention.cta}
									</Button>
								</div>
							</div>
						</section>
					</AnimatedSection>
				)}

				{/* ── Next FA: "coming up next" when working, "locked" when paused ── */}
				{nextArea && (
					<AnimatedSection index={4} transition={transition}>
						<section className="mb-10">
							<h2 className="text-foreground mb-4">
								{isPaused
									? 'Ready when you are'
									: 'Coming up next'}
							</h2>
							<div
								className={`rounded-lg p-5 ${
									isPaused
										? 'border border-neutral-200 bg-neutral-50/50'
										: 'border-2 border-dashed border-neutral-200 bg-neutral-50/30'
								}`}
							>
								<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(163, 163, 163, 0.15)',
										}}
									>
										{isPaused ? (
											<Lock className="w-5 h-5 text-neutral-400" />
										) : (
											<Clock className="w-5 h-5 text-neutral-400" />
										)}
									</div>
									<div className="flex-1 min-w-0">
										<h4 className="paragraph-semibold text-neutral-500 m-0!">
											{nextArea.title}
										</h4>
										<p
											className={`small-regular text-muted-foreground mt-1 m-0! ${isPaused ? '' : 'italic'}`}
										>
											{isPaused
												? nextArea.description
												: `"${nextArea.description}"`}
										</p>
									</div>
									{isPaused ? (
										<div className="flex flex-col items-end gap-1.5 shrink-0">
											<span className="inline-flex items-center gap-1 text-xs font-medium text-muted-foreground">
												<Lock className="w-3 h-3" />
												Locked
											</span>
											<a
												href={upgradeUrl}
												target="_blank"
												rel="noopener noreferrer"
												className="inline-flex items-center gap-1 small-semibold !text-magenta-500 hover:!text-magenta-700 transition-colors"
											>
												Unlock this improvement
												<ChevronRight className="w-4 h-4" />
											</a>
										</div>
									) : (
										<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-neutral-100 text-muted-foreground border border-neutral-200 shrink-0">
											Starting soon
										</span>
									)}
								</div>
							</div>
						</section>
					</AnimatedSection>
				)}

				{/* ── Completed work (always visible — falls back to initial-setup) ── */}
				<AnimatedSection index={5} transition={transition}>
					<section className="mb-10">
						<div
							className={`flex items-center justify-between ${isPaused ? 'mb-1' : 'mb-4'}`}
						>
							<h2 className="text-foreground m-0!">
								{isPaused
									? 'What Flavio already did'
									: 'Recent improvement'}
							</h2>
							<button
								type="button"
								onClick={() => onTimelineClick()}
								className={`inline-flex items-center gap-1.5 small-semibold transition-colors cursor-pointer shrink-0 ${
									isPaused
										? 'text-foreground hover:text-foreground/70'
										: 'text-magenta-500 hover:text-magenta-700'
								}`}
							>
								View all activity
								<ChevronRight className="w-4 h-4" />
							</button>
						</div>
						{isPaused && (
							<p className="small-regular text-muted-foreground mt-0! mb-4">
								Here are the improvements and checks completed
								during your trial.
							</p>
						)}

						<div className="rounded-xl border border-neutral-200 px-6 py-5">
							<div className="flex items-center gap-3 mb-3">
								<div
									className="w-10 h-10 rounded-lg flex items-center justify-center shrink-0"
									style={{
										backgroundColor:
											'rgba(51, 237, 119, 0.15)',
									}}
								>
									<CircleCheck className="w-5 h-5 text-green-500" />
								</div>
								<div>
									<p className="paragraph-semibold text-foreground m-0!">
										{recentFA.title}
									</p>
								</div>
							</div>
							{recentFA.description && (
								<p className="paragraph-regular text-muted-foreground m-0!">
									{recentFA.description}
								</p>
							)}
							{recentFA.lastDetail && (
								<div className="mt-4">
									<DetailRow task={recentFA.lastDetail} />
								</div>
							)}
						</div>
					</section>
				</AnimatedSection>
			</div>
		</main>
	);
};

export default DashboardPage;
