'use client';

import ArrowForwardRoundedIcon from '@mui/icons-material/ArrowForwardRounded';
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
import LocalOfferRoundedIcon from '@mui/icons-material/LocalOfferRounded';
import ShoppingBagRoundedIcon from '@mui/icons-material/ShoppingBagRounded';
import { type CSSProperties, useEffect, useMemo, useState } from 'react';
import type { PromotionConfig } from '../../config/defaultStoreConfig';
import { storeImageSrc } from '@/lib/storeImage';
import {
	PromotionActions,
	PromotionBadge,
	PromotionBody,
	PromotionClose,
	PromotionDescription,
	PromotionDialog,
	PromotionImage,
	PromotionLayout,
	PromotionMedia,
	PromotionMediaLabel,
	PromotionPrimaryAction,
	PromotionSecondaryAction,
	PromotionTitle
} from './styles';

type PromotionEntryDialogProps = {
	promotion: PromotionConfig;
	tenantKey: string;
	storeCssVariables: CSSProperties;
	onBuyNow: (category: string) => void;
};

function campaignHash(value: string) {
	let hash = 0;
	for (let index = 0; index < value.length; index += 1) {
		hash = (hash * 31 + value.charCodeAt(index)) | 0;
	}
	return Math.abs(hash).toString(36);
}

function isWithinSchedule(promotion: PromotionConfig) {
	const now = new Date();
	const start = promotion.popupStartDate ? new Date(`${promotion.popupStartDate}T00:00:00`) : null;
	const end = promotion.popupEndDate ? new Date(`${promotion.popupEndDate}T23:59:59`) : null;

	return (!start || now >= start) && (!end || now <= end);
}

function localDayKey(date = new Date()) {
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}-${month}-${day}`;
}

export default function PromotionEntryDialog({
	promotion,
	tenantKey,
	storeCssVariables,
	onBuyNow
}: PromotionEntryDialogProps) {
	const [open, setOpen] = useState(false);
	const title = promotion.popupTitle || promotion.heroTitle;
	const description = promotion.popupDescription || promotion.heroSubtitle;
	const image = promotion.popupImage || promotion.heroImage;
	const frequency = promotion.popupFrequency || 'oncePerSession';
	const storageKey = useMemo(() => {
		const signature = [
			tenantKey,
			title,
			image,
			promotion.popupTargetCategory,
			promotion.popupStartDate,
			promotion.popupEndDate
		].join('|');
		return `store_promotion_${campaignHash(signature)}`;
	}, [image, promotion.popupEndDate, promotion.popupStartDate, promotion.popupTargetCategory, tenantKey, title]);

	useEffect(() => {
		if (!promotion.popupEnabled || !title || !isWithinSchedule(promotion)) return;

		if (window.location.hash.startsWith('#/')) return;

		const today = localDayKey();
		const alreadySeen =
			frequency === 'oncePerSession'
				? sessionStorage.getItem(storageKey) === 'seen'
				: frequency === 'oncePerDay'
					? localStorage.getItem(storageKey) === today
					: false;

		if (alreadySeen) return;

		const timer = window.setTimeout(() => {
			if (frequency === 'oncePerSession') sessionStorage.setItem(storageKey, 'seen');

			if (frequency === 'oncePerDay') localStorage.setItem(storageKey, today);

			setOpen(true);
		}, 1150);
		return () => window.clearTimeout(timer);
	}, [frequency, promotion, storageKey, title]);

	const close = () => setOpen(false);
	const buyNow = () => {
		close();
		onBuyNow(promotion.popupTargetCategory || 'Todos');
	};

	return (
		<PromotionDialog
			open={open}
			onClose={close}
			aria-labelledby="store-promotion-title"
			slotProps={{ paper: { style: storeCssVariables } }}
		>
			<PromotionLayout>
				<PromotionClose
					type="button"
					aria-label="Cerrar promoción"
					onClick={close}
				>
					<CloseRoundedIcon />
				</PromotionClose>

				<PromotionMedia>
					<PromotionImage
						src={storeImageSrc(image, title)}
						alt={title}
					/>
					<PromotionMediaLabel>{promotion.popupBadge || promotion.heroBadge}</PromotionMediaLabel>
				</PromotionMedia>

				<PromotionBody>
					<PromotionBadge>
						<LocalOfferRoundedIcon />
						{promotion.popupBadge || 'Oferta especial'}
					</PromotionBadge>
					<PromotionTitle id="store-promotion-title">{title}</PromotionTitle>
					<PromotionDescription>{description}</PromotionDescription>
					<PromotionActions>
						<PromotionPrimaryAction
							type="button"
							onClick={buyNow}
						>
							<ShoppingBagRoundedIcon />
							{promotion.popupCtaLabel || 'Comprar ahora'}
							<ArrowForwardRoundedIcon />
						</PromotionPrimaryAction>
						<PromotionSecondaryAction
							type="button"
							onClick={close}
						>
							Ahora no
						</PromotionSecondaryAction>
					</PromotionActions>
				</PromotionBody>
			</PromotionLayout>
		</PromotionDialog>
	);
}
