import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import type { GoogleIntegrationEventDetail } from '@/lib/event';
import { cn } from '@/lib/utils';
import { useLocation, useNavigate } from '@tanstack/react-router';
import { __ } from '@wordpress/i18n';
import { Info } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';

const ALERT_CLASSES =
	'flex items-center gap-3 [&>svg]:translate-y-0 border-amber-200 bg-amber-50 text-amber-900 ';
const LINK_CLASSES =
	'h-auto px-0 text-sm! text-[#1D9E75] hover:text-[#0F6E56] cursor-pointer';

const ALERTS = {
	notConfigured: {
		message: __("Google Meet isn't configured yet.", 'allcoach'),
		cta: __('Set up Google Meet →', 'allcoach'),
	},
	notConnected: {
		message: __(
			"Google account isn't connected — meeting links won't be generated.",
			'allcoach',
		),
		cta: __('Connect Google Account →', 'allcoach'),
	},
} as const;

export function GoogleIntegrationAlert() {
	const navigate = useNavigate();
	const { pathname } = useLocation();
	const [isConfigured, setIsConfigured] = useState(
		__ALLCOACH_ADMIN__.googleIntegration.isConfigured,
	);
	const [isConnected, setIsConnected] = useState(
		__ALLCOACH_ADMIN__.googleIntegration.isConnected,
	);

	useEffect(() => {
		function handler(e: Event) {
			const { type, value } = (e as CustomEvent<GoogleIntegrationEventDetail>)
				.detail;
			if (type === 'configured') setIsConfigured(value);
			if (type === 'connected') setIsConnected(value);
		}
		window.addEventListener('allcoach:google-integration', handler);
		return () =>
			window.removeEventListener('allcoach:google-integration', handler);
	}, []);

	const wrapperClass = useMemo(
		() => cn(pathname.startsWith('/settings') && 'mx-auto max-w-7xl', 'mb-4'),
		[pathname],
	);

	const alert = !isConfigured
		? ALERTS.notConfigured
		: !isConnected
			? ALERTS.notConnected
			: null;

	if (!alert) return null;

	return (
		<Alert className={cn(wrapperClass, ALERT_CLASSES)}>
			<Info />
			<AlertDescription>
				{alert.message}{' '}
				<Button
					onClick={() => navigate({ to: '/settings/google-meet' })}
					variant="link"
					size="sm"
					className={LINK_CLASSES}
				>
					{alert.cta}
				</Button>
			</AlertDescription>
		</Alert>
	);
}
