'use client';

import KeyboardArrowUpRoundedIcon from '@mui/icons-material/KeyboardArrowUpRounded';
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
import { useEffect, useMemo, useState } from 'react';
import {
	BackToTopButton,
	FloatingActionHint,
	FloatingActionsRoot,
	floatingActionsReducedMotion,
	WhatsAppAction,
	WhatsAppCopy,
	WhatsAppIconShell
} from './floatingActionsStyles';

type StoreFloatingActionsProps = {
	whatsapp: string;
	storeName: string;
};

function normalizeWhatsAppNumber(value: string) {
	return value.replace(/\D/g, '');
}

export default function StoreFloatingActions({ whatsapp, storeName }: StoreFloatingActionsProps) {
	const [showBackToTop, setShowBackToTop] = useState(false);
	const [footerVisible, setFooterVisible] = useState(false);
	const whatsappNumber = normalizeWhatsAppNumber(whatsapp || '');
	const whatsappUrl = useMemo(() => {
		if (!whatsappNumber) return '';

		const message = encodeURIComponent(`Hola ${storeName}, quiero consultar sobre un producto de la tienda.`);
		return `https://wa.me/${whatsappNumber}?text=${message}`;
	}, [storeName, whatsappNumber]);

	useEffect(() => {
		const updateVisibility = () => setShowBackToTop(window.scrollY > 560);
		updateVisibility();
		window.addEventListener('scroll', updateVisibility, { passive: true });

		return () => window.removeEventListener('scroll', updateVisibility);
	}, []);

	useEffect(() => {
		const footer = document.querySelector('footer');

		if (!footer) return;

		const observer = new IntersectionObserver(([entry]) => setFooterVisible(entry.isIntersecting), {
			threshold: 0.02
		});
		observer.observe(footer);

		return () => observer.disconnect();
	}, []);

	const scrollToTop = () => {
		const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
		window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
	};

	const showWhatsApp = Boolean(whatsappUrl) && !footerVisible;

	if (!showWhatsApp && !showBackToTop) return null;

	return (
		<FloatingActionsRoot
			aria-label="Acciones rápidas de la tienda"
			sx={floatingActionsReducedMotion}
		>
			<BackToTopButton
				type="button"
				data-visible={showBackToTop}
				aria-label="Volver arriba"
				title="Volver arriba"
				onClick={scrollToTop}
			>
				<KeyboardArrowUpRoundedIcon />
				<FloatingActionHint aria-hidden="true">Volver arriba</FloatingActionHint>
			</BackToTopButton>

			{showWhatsApp && (
				<WhatsAppAction
					href={whatsappUrl}
					target="_blank"
					rel="noopener noreferrer"
					aria-label={`Consultar por WhatsApp a ${storeName}`}
					title="Consultar por WhatsApp"
				>
					<WhatsAppIconShell>
						<WhatsAppIcon />
					</WhatsAppIconShell>
					<WhatsAppCopy>
						<small>¿Necesitás ayuda?</small>
						<strong>Escribinos por WhatsApp</strong>
					</WhatsAppCopy>
				</WhatsAppAction>
			)}
		</FloatingActionsRoot>
	);
}
