import { useState } from 'react';
import { WandSparkles, Zap } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import {
	Dialog,
	DialogContent,
	DialogHeader,
	DialogTitle,
	DialogDescription,
} from '@/components/ui/dialog';
import useAutoMode from '@/features/interventions/useAutoMode';

/**
 * "Let Flavio handle these" nudge that switches the site to Automatic mode and
 * resolves the auto-resolvable interventions in one go. Shown only while the
 * site is in Review mode with at least one of them — the parent gates on
 * `agentMode === 'ask'` and `count > 0`.
 *
 * Switching to Automatic here always resolves them (no choice); the modal just
 * informs the user of the consequence before confirming.
 *
 * The copy carefully separates the two numbers: `total` is everything waiting in
 * the list, `count` is only what Flavio can take over. Saying "you've got 1
 * waiting" when 3 rows are on screen (and 2 of them still need the user) would
 * read as a lie.
 *
 * @param {object}   props
 * @param {'banner'|'nudge'} [props.variant]  Layout: full card in the list vs inline after a resolution.
 * @param {number}   props.count      How many pending interventions Flavio will resolve.
 * @param {number}   [props.total]    How many are pending in total (defaults to `count`).
 * @param {()=>void} [props.onEnabled] Called after the mode was switched successfully.
 */
const AutoModeBanner = ({ variant = 'banner', count = 0, total, onEnabled }) => {
	const { enable, pending, error } = useAutoMode();
	const [confirmOpen, setConfirmOpen] = useState(false);

	const handleConfirm = async () => {
		const ok = await enable({ resolvePending: true });
		if (ok) {
			setConfirmOpen(false);
			onEnabled?.();
		}
	};

	const pendingTotal = Math.max(total ?? count, count);
	// Some of what's waiting still needs the user (a decision, data only they
	// have), so Flavio can only take over part of the list.
	const partial = pendingTotal > count;
	const plural = count === 1 ? 'request' : 'requests';
	const them = count === 1 ? 'it' : 'them';

	const heading =
		variant === 'nudge'
			? 'Want me to handle the rest?'
			: 'Let me take it from here';

	const body = partial
		? `Of the ${pendingTotal} requests waiting, there ${count === 1 ? 'is 1' : `are ${count}`} I can resolve on my own. Switch to Automatic and I'll take care of ${them}, and keep handling routine fixes without pinging you each time.`
		: `You have ${count} pending ${plural} I can resolve for you. Switch to Automatic and I'll handle ${them} and keep things tidy from now on.`;

	// No "switched!" state here: on success the parent immediately stops
	// rendering this banner (the site is no longer in Review), and the list rows
	// take over the feedback with their "Resolving..." spinners.
	return (
		<div
			className={
				variant === 'nudge'
					? 'mt-6 rounded-xl border border-magenta-200 bg-magenta-50/60 p-4'
					: 'mb-8 rounded-2xl border border-magenta-200 bg-gradient-to-b from-magenta-50/70 to-transparent p-5'
			}
		>
			<div className="flex items-start gap-3">
				<span className="flex items-center justify-center size-9 rounded-xl bg-magenta-100 shrink-0">
					<WandSparkles className="w-4 h-4 text-magenta-500" />
				</span>
				<div className="flex-1 min-w-0">
					<p className="small-semibold text-foreground mt-0! mb-1!">
						{heading}
					</p>
					<p className="small-regular text-muted-foreground my-0!">
						{body}
					</p>
					{error && (
						<p className="small-regular text-destructive mt-2! mb-0!">
							{error}
						</p>
					)}
					<div className="mt-3">
						<Button
							type="button"
							onClick={() => setConfirmOpen(true)}
							className="bg-magenta-500 text-white! hover:bg-magenta-600"
						>
							<WandSparkles className="w-4 h-4" />
							Switch to Automatic
						</Button>
					</div>
				</div>
			</div>

			{/* Confirmation styled as a friendly heads-up rather than a yes/no
			    dialog: one full-width primary action and a low-key text link to
			    dismiss, so switching reads as the natural next step. */}
			<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
				<DialogContent className="max-w-md">
					<DialogHeader>
						<DialogTitle>Want me to take it from here?</DialogTitle>
						<DialogDescription>
							{variant === 'nudge' && "That one's live. "}
							{partial ? (
								<>
									Of the {pendingTotal} requests waiting,
									there{' '}
									<strong className="text-foreground">
										{count === 1
											? 'is 1 I can resolve'
											: `are ${count} I can resolve`}
									</strong>{' '}
									on my own. The {pendingTotal - count}{' '}
									{pendingTotal - count === 1
										? 'other still needs'
										: 'others still need'}{' '}
									you.
								</>
							) : (
								<>
									You've got{' '}
									<strong className="text-foreground">
										{count} {plural}
									</strong>{' '}
									waiting for review.
								</>
							)}{' '}
							Switch to Automatic and I'll resolve {them} myself,
							and keep handling routine fixes without pinging you
							each time.
						</DialogDescription>
					</DialogHeader>
					{/* The banner behind the modal also renders `error`, but that is
					    hidden while the dialog is open, so surface it here too. */}
					{error && (
						<p className="small-regular text-destructive text-center my-0!">
							{error}
						</p>
					)}
					<div className="mt-2 flex flex-col items-center gap-1">
						<Button
							type="button"
							size="lg"
							className="w-full"
							onClick={handleConfirm}
							disabled={pending}
						>
							{pending ? (
								<Spinner className="size-4" />
							) : (
								<Zap className="w-4 h-4" />
							)}
							Switch to Automatic & resolve {count}
						</Button>
						<Button
							type="button"
							variant="link"
							className="text-muted-foreground"
							onClick={() => setConfirmOpen(false)}
							disabled={pending}
						>
							{variant === 'nudge'
								? 'Just this one for now'
								: 'Not now'}
						</Button>
					</div>
				</DialogContent>
			</Dialog>
		</div>
	);
};

export default AutoModeBanner;
