import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { FaTimes, FaCheck, FaArrowRight, FaInfoCircle, FaExclamationTriangle } from 'react-icons/fa';
import './noticemodal.scss';

const NoticeModal = ({ isOpen, onClose, onConfirm, onDecline,
    type = 'confirmation', // 'confirmation', 'premium', 'toast'
    title,
    message,
    confirmText = 'Confirm',
    declineText = 'Cancel',
    position = 'center', // 'center', 'top-right', 'bottom-right'
    autoClose = false,
    autoCloseTime = 3000,
    icon = null,
    mode = 'success', // 'success', 'info', 'warning', 'error'
}) => {

    const [selectedPlan, setSelectedPlan] = useState('Lifetime');
    const [isMobile, setIsMobile] = useState(false);

    // Responsive check
    useEffect(() => {
        const checkMobileView = () => {
            setIsMobile(window.innerWidth <= 768);
        };

        // Check initial load
        checkMobileView();

        // Add resize listener
        window.addEventListener('resize', checkMobileView);

        return () => {
            window.removeEventListener('resize', checkMobileView);
        };
    }, []);
    // Close modal when Escape key is pressed
    useEffect(() => {
        const handleEsc = (event) => {
            if (event.keyCode === 27) onClose();
        };
        window.addEventListener('keydown', handleEsc);

        return () => {
            window.removeEventListener('keydown', handleEsc);
        };
    }, [onClose]);

    // Prevent body scrolling when modal is open (only for center modals)
    useEffect(() => {
        if (isOpen && position === 'center') {
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = 'unset';
        }
        return () => {
            document.body.style.overflow = 'unset';
        };
    }, [isOpen, position]);

    // Auto close for toast notifications
    useEffect(() => {
        if (isOpen && window.FS) {
            window.handler = window.FS.Checkout.configure({
                plugin_id: '14342',
                plan_id: '23982',
                public_key: 'pk_bc3d08a262990e44dee3cb5bb42a8',
                image: ''
            });
        }
    }, [isOpen, autoClose, autoCloseTime, onClose]);

    const plans = {
        Yearly: {
            basic: {
                price: '$19.99',
                originalPrice: '$99.95',
                discount: '80%',
                siteCount: '1',
                features: ['All Basic features', 'WooCommerce packages', 'Advanced security packages', 'Kick out', 'Priority support']
            },
            pro: {
                price: '$35.14',
                originalPrice: '$175.70',
                discount: '80%',
                siteCount: '5',
                features: ['All Basic features', 'WooCommerce packages', 'Advanced security packages', 'Kick out', 'Priority support']
            },
            agency: {
                price: '$80.49',
                originalPrice: '$402.45',
                discount: '80%',
                siteCount: '50',
                features: ['All Basic features', 'WooCommerce packages', 'Advanced security packages', 'Kick out', 'Priority support']
            }
        },
        Lifetime: {
            basic: {
                price: '$30.49',
                originalPrice: '$152.45',
                discount: '80%',
                siteCount: '1',
                features: ['All Basic features', 'WooCommerce packages', 'Advanced security packages', 'Visitor traffic and Kick out', 'Priority support']
            },
            pro: {
                price: '$85.35',
                originalPrice: '$426.75',
                discount: '80%',
                siteCount: '5',
                features: ['All Basic features', 'WooCommerce packages', 'Advanced security packages', 'Kick out', 'Priority support']
            },
            agency: {
                price: '$150.20',
                originalPrice: '$751.00',
                discount: '80%',
                siteCount: '50',
                features: ['All Basic features', 'WooCommerce packages', 'Advanced security packages', 'Kick out', 'Priority support']
            }
        }
    };

    const handlePurchase = (plan, planType) => {
        const siteCount = plans[planType][plan].siteCount;

        if (window.handler) {
            window.handler.open({
                name: 'Activity Guard',
                licenses: siteCount,
                billing_cycle: planType === 'Lifetime' ? 'lifetime' : 'annual',
                success: function (response) {
                    window.location.href = 'functiondeck.com/after-purchase/?email=' +
                        encodeURIComponent(response.user.email) +
                        '&first=' + encodeURIComponent(response.user.first) +
                        '&last=' + encodeURIComponent(response.user.last);
                }
            });
        } else {
            console.error('Freemius checkout handler not initialized');
            // Fallback to onConfirm if handler not available
            onConfirm(plan, planType);
        }
    };

    // Get the appropriate icon for toasts based on type
    const getToastIcon = () => {
        if (icon) return icon;

        console.log(mode)

        switch (mode) {
            case 'success':
                return <FaCheck />;
            case 'info':
                return <FaInfoCircle />;
            case 'warning':
                return <FaExclamationTriangle />;
            case 'error':
                return <FaExclamationTriangle />;
            default:
                return <FaCheck />;
        }
    };

    // Render different modal types
    const renderModalContent = () => {
        switch (type) {
            case 'confirmation':
                return (
                    <div className="notice-modal-confirmation">
                        <div className="notice-modal-header">
                            <h2>{title || 'Confirmation'}</h2>
                            <p>{message || 'Are you sure you want to proceed?'}</p>
                            <button className="notice-modal-close" onClick={onClose}>
                                <FaTimes />
                            </button>
                        </div>

                        <div className="notice-modal-actions">
                            <button
                                className="notice-modal-decline"
                                onClick={onDecline || onClose}
                            >
                                {declineText}
                            </button>
                            <button
                                className="notice-modal-confirm"
                                onClick={onConfirm}
                            >
                                {confirmText} <FaArrowRight className="arrow-icon" />
                            </button>
                        </div>
                    </div>
                );

            case 'premium':
                return (
                    <div className={`price-modal-container ${isMobile ? 'mobile' : ''}`}>
                        <div className="price-modal-header">
                            <h2>{title || '🚀 Oops! This is a Premium Feature'}</h2>
                            <p>{message || 'Upgrade now to unlock this premium feature!'}</p>
                            <button className="price-modal-close" onClick={onClose}>
                                <FaTimes />
                            </button>
                        </div>

                        <div className="price-modal-toggle">
                            {['Yearly', 'Lifetime'].map(planType => (
                                <button
                                    key={planType}
                                    className={selectedPlan === planType ? 'active' : ''}
                                    onClick={() => setSelectedPlan(planType)}
                                >
                                    {planType}
                                    {planType === 'Lifetime' && (
                                        <span className="price-modal-save">Save 80%</span>
                                    )}
                                </button>
                            ))}
                        </div>

                        <div className="price-modal-plans">
                            {['basic', 'pro', 'agency'].map((plan) => (
                                <div
                                    key={plan}
                                    className={`price-modal-plan ${plan === 'pro' ? 'recommended' : ''}`}
                                >
                                    {plan === 'pro' && (
                                        <div className="price-modal-recommended">
                                            MOST POPULAR
                                        </div>
                                    )}
                                    <h3>{plan.charAt(0).toUpperCase() + plan.slice(1)}</h3>

                                    <div className="price-modal-price">
                                        <div className="price-modal-original">
                                            {plans[selectedPlan][plan].originalPrice}
                                        </div>
                                        <div className="price-modal-discount">
                                            -{plans[selectedPlan][plan].discount}
                                        </div>
                                        <div className="price-modal-current">
                                            {plans[selectedPlan][plan].price}
                                        </div>
                                        <div className="price-modal-period">
                                            /{selectedPlan === 'Yearly' ? 'Year' : 'Lifetime'}
                                        </div>
                                    </div>

                                    <ul className="price-modal-features">
                                        {plans[selectedPlan][plan].features.map((feature, index) => (
                                            <li key={index}>
                                                <FaCheck className="check-icon" />
                                                {feature}
                                            </li>
                                        ))}
                                    </ul>

                                    <button
                                        className="price-modal-select"
                                        onClick={() => handlePurchase(plan, selectedPlan)}
                                    >
                                        {confirmText} <FaArrowRight className="arrow-icon" />
                                    </button>
                                </div>
                            ))}
                        </div>

                        <div className="price-modal-guarantee">
                            <div className="price-modal-guarantee-badge">14</div>
                            <div className="price-modal-guarantee-text">
                                <h4>14-Day Money-Back Guarantee</h4>
                                <p>Try it risk-free. If you're not satisfied, get a full refund within 14 days.</p>
                            </div>
                        </div>
                    </div>
                );

            case 'premium-14-days-notice':
                return (
                    <div className="notice-modal-premium">
                        <div className="notice-modal-header">
                            <h2>{title || '🚀 Oops! This is a Premium Feature'}</h2>
                            <p>{message || 'Upgrade now to unlock this premium feature!'}</p>
                            <button className="notice-modal-close" onClick={onClose}>
                                <FaTimes />
                            </button>
                        </div>

                        <div className="notice-modal-guarantee">
                            <div className="notice-modal-guarantee-badge">14</div>
                            <div className="notice-modal-guarantee-text">
                                <h4>14-Day Money-Back Guarantee</h4>
                                <p>Try it risk-free. If you're not satisfied, get a full refund within 14 days.</p>
                            </div>
                        </div>

                        <div className="notice-modal-actions">
                            <button
                                className="notice-modal-decline"
                                onClick={onDecline || onClose}
                            >
                                {declineText}
                            </button>
                            <button
                                className="notice-modal-confirm"
                                onClick={onConfirm}
                            >
                                {confirmText} <FaArrowRight className="arrow-icon" />
                            </button>
                        </div>
                    </div>
                );

            case 'toast':
                return (
                    <div className={`notice-modal-toast notice-modal-toast-${position} notice-border-left-${mode}`}>
                        <div className={`notice-modal-toast-icon ${mode}`}>
                            {getToastIcon()}
                        </div>
                        <div className="notice-modal-toast-content">
                            <h4 className={`${mode}`}>{title || 'Notification'}</h4>
                            <p>{message || 'Operation completed successfully.'}</p>
                        </div>
                        <button className="notice-modal-toast-close" onClick={onClose}>
                            <FaTimes />
                        </button>
                    </div>
                );

            default:
                return null;
        }
    };

    // Animation variants based on position
    const getAnimationVariants = () => {
        if (position === 'top-right') {
            return {
                initial: { opacity: 0, x: 50 },
                animate: { opacity: 1, x: 0 },
                exit: { opacity: 0, x: 50 }
            };
        } else if (position === 'bottom-right') {
            return {
                initial: { opacity: 0, x: 50 },
                animate: { opacity: 1, x: 0 },
                exit: { opacity: 0, x: 50 }
            };
        } else {
            return {
                initial: { opacity: 0, y: 50 },
                animate: { opacity: 1, y: 0 },
                exit: { opacity: 0, y: 50 }
            };
        }
    };

    return (
        <AnimatePresence>
            {isOpen && (
                <>
                    {/* Only show overlay for center modals */}
                    {position === 'center' && (
                        <motion.div
                            className="notice-modal-overlay-price"
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            onClick={onClose}
                        />
                    )}

                    <motion.div
                        className={`notice-modal-container notice-modal-${position}`}
                        {...getAnimationVariants()}
                        transition={{ type: 'spring', damping: 25, stiffness: 500 }}
                    >
                        {renderModalContent()}
                    </motion.div>
                </>
            )}
        </AnimatePresence>
    );
};

export default NoticeModal;