'use client';

import EmailRoundedIcon from '@mui/icons-material/EmailRounded';
import ArrowUpwardRoundedIcon from '@mui/icons-material/ArrowUpwardRounded';
import FacebookIcon from '@mui/icons-material/Facebook';
import InstagramIcon from '@mui/icons-material/Instagram';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import LocalShippingRoundedIcon from '@mui/icons-material/LocalShippingRounded';
import LocationOnRoundedIcon from '@mui/icons-material/LocationOnRounded';
import PhoneRoundedIcon from '@mui/icons-material/PhoneRounded';
import SecurityRoundedIcon from '@mui/icons-material/SecurityRounded';
import SupportAgentRoundedIcon from '@mui/icons-material/SupportAgentRounded';
import WhatsAppIcon from '@mui/icons-material/WhatsApp';
import type { SvgIconComponent } from '@mui/icons-material';
import { DEFAULT_STORE_CONFIG, type StoreConfig } from '../../config/defaultStoreConfig';
import { BrandMark } from '../layout/styles';
import {
	FooterBottom,
	FooterBottomCopy,
	FooterBottomInner,
	FooterBottomLeft,
	FooterBottomRight,
	FooterBackToTop,
	FooterContactItem,
	FooterContactList,
	FooterColumnTitle,
	FooterInner,
	FooterLead,
	FooterLeadActions,
	FooterLeadBrand,
	FooterLeadCopy,
	FooterPrimaryAction,
	FooterSecondaryAction,
	FooterLinks,
	FooterLinkItem,
	FooterSection,
	FooterSocialBtn,
	FooterTrustGrid,
	FooterTrustItem,
	FooterTopPaymentGroup,
	FooterTopPaymentLabel,
	FooterTopSocialGroup,
	FooterTopSocialLabel,
	FooterTopStrip,
	FooterTopStripInner,
	PaymentPill,
	StoreFooter
} from './styles';

const SOCIAL_ICONS: Record<string, SvgIconComponent> = {
	instagram: InstagramIcon,
	facebook: FacebookIcon,
	linkedin: LinkedInIcon,
	whatsapp: WhatsAppIcon
};

function TikTokIcon({ style }: { style?: React.CSSProperties }) {
	return (
		<svg
			viewBox="0 0 24 24"
			width="1em"
			height="1em"
			fill="currentColor"
			style={style}
		>
			<path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.33 6.33 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.33-6.34V8.75a8.27 8.27 0 0 0 4.84 1.55V6.85a4.85 4.85 0 0 1-1.07-.16z" />
		</svg>
	);
}

function getSocialIcon(label: string) {
	const key = label.toLowerCase();

	if (key === 'tiktok') return TikTokIcon;

	return SOCIAL_ICONS[key] ?? null;
}

function formatFooterTemplate(template: string, year: number, storeName: string) {
	return template.replaceAll('{year}', String(year)).replaceAll('{store}', storeName);
}

type StoreFooterSectionProps = {
	config: StoreConfig;
	onOpenContentPage: (pageKey: string) => void;
};

function StoreFooterSection({ config, onOpenContentPage }: StoreFooterSectionProps) {
	const { contact } = config.footer;
	const labels = { ...DEFAULT_STORE_CONFIG.footer.labels, ...(config.footer.labels ?? {}) };
	const whatsappNumber = (contact.whatsapp ?? '').replace(/\D/g, '');
	const linkGroups = (config.footer.linkGroups ?? [])
		.filter((group) => group.enabled !== false)
		.map((group) => ({
			...group,
			links: (group.links ?? []).filter(
				(link) =>
					link.enabled !== false &&
					Boolean(link.label?.trim()) &&
					Boolean(link.pageKey?.trim() || link.href?.trim())
			)
		}))
		.filter((group) => group.links.length > 0);
	const socialLinks = (config.footer.socialLinks ?? []).filter(
		(link) => link.enabled !== false && Boolean(link.label?.trim()) && Boolean(link.href?.trim())
	);
	const paymentMethods = (config.footer.paymentMethods ?? []).filter(
		(method) => typeof method === 'string' && method.trim().length > 0
	);
	const year = new Date().getFullYear();
	const hasSocial = socialLinks.length > 0;
	const hasPayment = paymentMethods.length > 0;
	const deliveryLabel =
		config.checkout.allowDelivery && config.checkout.allowPickup
			? labels.deliveryAndPickup
			: config.checkout.allowDelivery
				? labels.deliveryOnly
				: labels.pickupOnly;
	const secondaryContactHref = contact.email
		? `mailto:${contact.email}`
		: contact.phone
			? `tel:${contact.phone.replace(/\s/g, '')}`
			: '#';

	return (
		<StoreFooter>
			<FooterLead>
				<FooterLeadBrand>
					<BrandMark>{config.identity.logoText}</BrandMark>
					<FooterLeadCopy>
						<small>{labels.leadEyebrow}</small>
						<h2>{config.identity.slogan || config.identity.name}</h2>
						<p>{config.footer.description}</p>
					</FooterLeadCopy>
				</FooterLeadBrand>

				<FooterTrustGrid>
					<FooterTrustItem>
						<span>
							<SecurityRoundedIcon />
						</span>
						<div>
							<strong>{labels.paymentTrustTitle}</strong>
							<small>{config.checkout.paymentProviderLabel}</small>
						</div>
					</FooterTrustItem>
					<FooterTrustItem>
						<span>
							<LocalShippingRoundedIcon />
						</span>
						<div>
							<strong>{labels.deliveryTrustTitle}</strong>
							<small>{deliveryLabel}</small>
						</div>
					</FooterTrustItem>
					<FooterTrustItem>
						<span>
							<SupportAgentRoundedIcon />
						</span>
						<div>
							<strong>{labels.supportTrustTitle}</strong>
							<small>{contact.hours || contact.phone}</small>
						</div>
					</FooterTrustItem>
				</FooterTrustGrid>

				<FooterLeadActions>
					{whatsappNumber && (
						<FooterPrimaryAction
							href={`https://wa.me/${whatsappNumber}`}
							target="_blank"
							rel="noreferrer"
						>
							<WhatsAppIcon /> {labels.whatsappAction}
						</FooterPrimaryAction>
					)}
					{(contact.email || contact.phone) && (
						<FooterSecondaryAction href={secondaryContactHref}>
							{contact.email ? <EmailRoundedIcon /> : <PhoneRoundedIcon />} {labels.contactAction}
						</FooterSecondaryAction>
					)}
				</FooterLeadActions>
			</FooterLead>

			<FooterInner>
				{/* Columnas del medio: grupos de links */}
				{linkGroups.map((group) => (
					<FooterSection key={group.id ?? group.title}>
						<FooterColumnTitle>{group.title}</FooterColumnTitle>
						<FooterLinks>
							{group.links.map((link, index) => {
								const handleClick = () => {
									if (link.pageKey) {
										onOpenContentPage(link.pageKey as string);
									} else if (link.href) {
										if (link.href.startsWith('#')) {
											const el = document.getElementById(link.href.slice(1));

											if (el) el.scrollIntoView({ behavior: 'smooth' });
										} else {
											window.open(link.href, '_self');
										}
									}
								};
								return (
									<FooterLinkItem
										key={link.id ?? `${link.label}-${index}`}
										as="button"
										type="button"
										onClick={handleClick}
									>
										{link.label}
									</FooterLinkItem>
								);
							})}
						</FooterLinks>
					</FooterSection>
				))}

				{/* Última columna: contacto */}
				<FooterSection data-contact="true">
					<FooterColumnTitle>{labels.contactColumnTitle}</FooterColumnTitle>
					<FooterContactList>
						{contact.address && (
							<FooterContactItem
								href={contact.map?.directionsUrl ?? '#'}
								target="_blank"
								rel="noreferrer"
							>
								<LocationOnRoundedIcon style={{ fontSize: 15, flexShrink: 0 }} />
								<span>{contact.address}</span>
							</FooterContactItem>
						)}
						{contact.email && (
							<FooterContactItem href={`mailto:${contact.email}`}>
								<EmailRoundedIcon style={{ fontSize: 15, flexShrink: 0 }} />
								<span>{contact.email}</span>
							</FooterContactItem>
						)}
						{contact.phone && (
							<FooterContactItem href={`tel:${contact.phone.replace(/\s/g, '')}`}>
								<PhoneRoundedIcon style={{ fontSize: 15, flexShrink: 0 }} />
								<span>{contact.phone}</span>
							</FooterContactItem>
						)}
						{whatsappNumber && (
							<FooterContactItem
								href={`https://wa.me/${whatsappNumber}`}
								target="_blank"
								rel="noreferrer"
								data-whatsapp="true"
							>
								<WhatsAppIcon style={{ fontSize: 15, flexShrink: 0 }} />
								<span>{contact.whatsapp}</span>
							</FooterContactItem>
						)}
						{contact.hours && (
							<FooterContactItem as="span">
								<span style={{ opacity: 0.55, fontSize: 12 }}>{contact.hours}</span>
							</FooterContactItem>
						)}
					</FooterContactList>
				</FooterSection>
			</FooterInner>

			{(hasSocial || hasPayment) && (
				<FooterTopStrip>
					<FooterTopStripInner>
						{hasSocial && (
							<FooterTopSocialGroup>
								<FooterTopSocialLabel>{labels.socialTitle}</FooterTopSocialLabel>
								{socialLinks.map((link, index) => {
									const Icon = getSocialIcon(link.label);
									return (
										<FooterSocialBtn
											key={`${link.label}-${index}`}
											href={link.href}
											target="_blank"
											rel="noreferrer"
											aria-label={link.label}
											data-network={link.label.toLowerCase()}
										>
											{Icon ? (
												<Icon style={{ fontSize: 19 }} />
											) : (
												<span>{link.label.slice(0, 2).toUpperCase()}</span>
											)}
										</FooterSocialBtn>
									);
								})}
							</FooterTopSocialGroup>
						)}
						{hasPayment && (
							<FooterTopPaymentGroup>
								<FooterTopPaymentLabel>{labels.paymentsTitle}</FooterTopPaymentLabel>
								{paymentMethods.map((method, index) => (
									<PaymentPill key={`${method}-${index}`}>{method}</PaymentPill>
								))}
							</FooterTopPaymentGroup>
						)}
					</FooterTopStripInner>
				</FooterTopStrip>
			)}

			{/* ── Barra inferior: copyright ──────────────────────────────────── */}
			<FooterBottom>
				<FooterBottomInner>
					<FooterBottomLeft>
						<FooterBottomCopy>
							{formatFooterTemplate(labels.copyrightTemplate, year, config.identity.name)}
						</FooterBottomCopy>
					</FooterBottomLeft>
					<FooterBottomRight>
						{config.texts?.poweredByLabel && <span>{config.texts.poweredByLabel}</span>}
						<FooterBackToTop
							type="button"
							aria-label="Volver arriba"
							onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
						>
							<ArrowUpwardRoundedIcon />
						</FooterBackToTop>
					</FooterBottomRight>
				</FooterBottomInner>
			</FooterBottom>
		</StoreFooter>
	);
}

export default StoreFooterSection;
