import {
	ArrowLeft,
	ChevronRight,
	Clock,
	PauseCircle,
	CircleCheck,
	PenLine,
	ExternalLink,
	ListChecks,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { getWordPressConfig } from '@/api/client';
import useInterventions from '@/hooks/useInterventions';
import useAreas from '@/hooks/useAreas';
import { getAreaName } from '@/hooks/useTimeline';
import AreaChip from '@/features/interventions/AreaChip';

/** "2026-03-02 14:30:00" → "Today" | "Yesterday" | "Mar 2". */
const formatRelativeDate = (raw) => {
	if (!raw) return '';
	const date = new Date(raw.replace(' ', 'T'));
	if (Number.isNaN(date.getTime())) return '';
	const startOfDay = (d) =>
		new Date(d.getFullYear(), d.getMonth(), d.getDate());
	const days = Math.round(
		(startOfDay(new Date()) - startOfDay(date)) / 86400000
	);
	if (days <= 0) return 'Today';
	if (days === 1) return 'Yesterday';
	if (days < 7) return `${days} days ago`;
	return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
};

/** The single blocking intervention — the urgent, progress-paused hero card. */
const BlockingHero = ({ item, onOpen }) => {
	const { Icon } = item;
	return (
		<div className="rounded-xl border border-amber-300 bg-amber-50 p-6">
			<div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 mb-6">
				<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
					<span className="inline-flex items-center gap-1.5 rounded-full border border-amber-300 bg-amber-100/70 px-3 py-1 small-medium text-amber-700">
						<PauseCircle className="w-4 h-4" />
						Progress paused
					</span>
					<span className="small-medium text-amber-700">
						Waiting on you
						{item.areaName && (
							<>
								{' · '}
								<span className="font-semibold">
									{item.areaName}
								</span>
							</>
						)}
					</span>
				</div>
				{item.createdAt && (
					<span className="inline-flex items-center gap-1.5 small-regular text-amber-700/70 whitespace-nowrap">
						<Clock className="w-3.5 h-3.5" />
						{formatRelativeDate(item.createdAt)}
					</span>
				)}
			</div>

			<div className="flex items-start gap-3 mb-3">
				{Icon && (
					<span className="flex items-center justify-center w-10 h-10 rounded-lg bg-amber-100 shrink-0">
						<Icon className="w-5 h-5 text-amber-600" />
					</span>
				)}
				<h2 className="heading-h2 mt-0! leading-tight">{item.title}</h2>
			</div>

			{item.description && (
				<p className="paragraph-regular text-foreground/80 mb-7">
					{item.description}
				</p>
			)}

			<Button type="button" onClick={() => onOpen?.(item.id)}>
				{item.cta}
				<ChevronRight />
			</Button>
		</div>
	);
};

/** A non-blocking intervention row inside the inbox. */
const InboxItem = ({ item, onOpen }) => {
	const { Icon } = item;
	return (
		<div className="flex items-center gap-4 rounded-xl border border-border bg-card p-4 transition-colors hover:border-neutral-300">
			<span className="flex items-center justify-center w-10 h-10 rounded-lg bg-amber-100 shrink-0">
				{Icon && <Icon className="w-5 h-5 text-amber-600" />}
			</span>

			<div className="min-w-0 flex-1">
				<p className="paragraph-semibold text-foreground mt-0! mb-1!">
					{item.title}
				</p>
				{item.description && (
					<p className="small-regular text-muted-foreground line-clamp-1 my-0!">
						{item.description}
					</p>
				)}
			</div>

			<AreaChip areaKey={item.areaKey} className="hidden sm:inline-flex" />
			<span className="text-xs text-muted-foreground whitespace-nowrap shrink-0">
				{formatRelativeDate(item.createdAt)}
			</span>

			<Button
				type="button"
				variant="outline"
				size="sm"
				onClick={() => onOpen?.(item.id)}
			>
				{item.cta}
				<ChevronRight />
			</Button>
		</div>
	);
};

/** The categories Flavio reaches out for — static, explanatory. */
const PING_CATEGORIES = [
	{
		Icon: CircleCheck,
		title: 'Validation',
		description: "Approve or revert a change I've drafted.",
	},
	{
		Icon: PenLine,
		title: 'Data input',
		description: "Fill in info I can't find on your own site.",
	},
	{
		Icon: ExternalLink,
		title: 'External action',
		description: 'Do something outside WP, like enabling SSL.',
	},
	{
		Icon: ListChecks,
		title: 'Choice',
		description: "Pick from options I've drafted for you.",
	},
];

/**
 * Shown when there are no pending interventions: reassures the user that Flavio
 * is working on its own. Pulls the current Focus Area + progress from /areas
 * (only fetched while this is mounted, i.e. only when the inbox is empty).
 */
const EmptyState = ({ mascot, onViewActivity }) => {
	const { currentArea, currentProgress } = useAreas();
	const areaShortName = currentArea ? getAreaName(currentArea.key) : null;

	return (
		<>
			<div className="rounded-2xl border border-border bg-gradient-to-b from-magenta-50/40 to-transparent p-10 text-center">
				<span className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-magenta-100 mb-5">
					<img
						src={mascot}
						alt="Flavio"
						className="size-9"
						aria-hidden="true"
					/>
				</span>

				<h2 className="heading-h2 mt-0! mb-3">
					All clear. I've got this
				</h2>
				<div className="max-w-md mx-auto mb-6 mt-4">
					<p className="paragraph-regular text-muted-foreground my-0!">
						Nothing needs your input right now.
						{areaShortName
							? ` I'm working in the background on ${areaShortName}.`
							: " I'm working in the background."}{' '}
						I'll ping you only if I really need you.
					</p>
				</div>

				{currentArea && (
					<div className="inline-flex flex-wrap items-center justify-center gap-x-2 gap-y-1 rounded-full bg-magenta-50 px-4 py-2 mb-6">
						<span className="w-2 h-2 rounded-full bg-magenta-500 shrink-0" />
						<span className="small-medium text-magenta-600">
							Currently improving
						</span>
						<span className="text-muted-foreground">·</span>
						<span className="small-semibold text-foreground">
							{currentArea.title}
						</span>
						<span className="text-muted-foreground">·</span>
						<span className="small-medium text-magenta-600">
							{currentProgress}%
						</span>
					</div>
				)}

				<div>
					<Button
						type="button"
						variant="outline"
						onClick={onViewActivity}
					>
						View activity log
					</Button>
				</div>
			</div>

			<div className="mt-8">
				<p className="label-semibold uppercase tracking-wider text-muted-foreground mb-4">
					What I'll ping you for
				</p>
				<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
					{PING_CATEGORIES.map((category) => (
						<div
							key={category.title}
							className="flex items-start gap-3 rounded-xl border border-dashed border-border p-4"
						>
							<span className="flex items-center justify-center w-9 h-9 rounded-lg bg-neutral-100 shrink-0">
								<category.Icon className="w-4 h-4 text-neutral-500" />
							</span>
							<div>
								<p className="small-semibold text-foreground mt-0! mb-0.5!">
									{category.title}
								</p>
								<p className="small-regular text-muted-foreground my-0!">
									{category.description}
								</p>
							</div>
						</div>
					))}
				</div>
			</div>
		</>
	);
};

/**
 * InterventionsPage ("Needs your attention")
 *
 * Lists the pending interventions Flavio needs the user to act on. The blocking
 * one (if any) is surfaced as a hero card; the rest land in the inbox list.
 */
const InterventionsPage = ({
	onBack,
	transition,
	onViewActivity,
	onOpenIntervention,
}) => {
	const config = getWordPressConfig();
	const { blocking, inbox, loading, error, isEmpty, retry } =
		useInterventions();

	const transitionClass =
		transition === 'action-enter'
			? 'animate-slide-in-from-right'
			: transition === 'action-exit'
				? 'animate-slide-out-to-right'
				: '';

	const subtitle = blocking
		? inbox.length > 0
			? 'One thing is blocking me. The rest can wait until you have a minute.'
			: "One thing is blocking me. Let's get it sorted."
		: "Here's what I'd like your input on. Take them whenever you have a minute.";

	const mascot = `${config?.pluginUrl || ''}js/public/onboarding.svg`;

	return (
		<main className={`flex-1 pt-8 pb-24 ${transitionClass}`}>
			<div className="max-w-3xl mx-auto px-8">
				<button
					type="button"
					onClick={onBack}
					className="inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors cursor-pointer mb-6"
				>
					<ArrowLeft className="w-4 h-4" />
					Back
				</button>

				{/* Header (hidden in the empty state, which has its own hero) */}
				{!isEmpty && (
					<div className="flex items-center gap-3 mb-2">
						<img
							src={mascot}
							alt="Flavio"
							className="size-10 shrink-0"
							aria-hidden="true"
						/>
						<h1 className="heading-h1 mt-0! leading-tight">
							Needs your attention
						</h1>
					</div>
				)}
				{!loading && !error && !isEmpty && (
					<p className="paragraph-regular text-muted-foreground mb-10">
						{subtitle}
					</p>
				)}

				{/* Loading */}
				{loading && (
					<div className="space-y-3 mt-8">
						<Skeleton className="h-40 w-full rounded-xl" />
						<Skeleton className="h-20 w-full rounded-xl" />
						<Skeleton className="h-20 w-full rounded-xl" />
					</div>
				)}

				{/* Error */}
				{!loading && error && (
					<div className="mt-8 rounded-xl border border-border bg-card p-8 text-center">
						<p className="paragraph-regular text-foreground mb-4">
							I couldn't load this right now.
						</p>
						<Button type="button" variant="outline" onClick={retry}>
							Try again
						</Button>
					</div>
				)}

				{/* Empty */}
				{!loading && !error && isEmpty && (
					<EmptyState mascot={mascot} onViewActivity={onViewActivity} />
				)}

				{/* Content */}
				{!loading && !error && !isEmpty && (
					<>
						{blocking && (
							<BlockingHero
								item={blocking}
								onOpen={onOpenIntervention}
							/>
						)}

						{inbox.length > 0 && (
							<section className={blocking ? 'mt-10' : 'mt-2'}>
								<div className="flex flex-wrap items-baseline gap-x-2 mb-4">
									<h2 className="heading-h4 mt-0!">
										In your inbox
									</h2>
									<span className="small-regular text-muted-foreground">
										{inbox.length}{' '}
										{inbox.length === 1 ? 'item' : 'items'} ·
										won't block other improvements
									</span>
								</div>
								<div className="space-y-3">
									{inbox.map((item) => (
										<InboxItem
											key={item.id}
											item={item}
											onOpen={onOpenIntervention}
										/>
									))}
								</div>
							</section>
						)}
					</>
				)}
			</div>
		</main>
	);
};

export default InterventionsPage;
