import React, { useState } from "react";
import { getNonce, getAjaxUrl, isPro } from '../Helpers';
import { isThemeLocked, getThemeLockModalConfig } from '../FreeTierLimits';
import ConfirmModal from './ConfirmModal';
import NoticeModal from './NoticeModal/NoticeModal';
const Screenshot_1 = require('../../../assets/public/theme/Screenshot_1.png');
const Screenshot_2 = require('../../../assets/public/theme/Screenshot_2.png');
const Screenshot_3 = require('../../../assets/public/theme/Screenshot_3.png');
const Screenshot_4 = require('../../../assets/public/theme/Screenshot_4.png');
const Screenshot_5 = require('../../../assets/public/theme/Screenshot_5.png');
const Screenshot_6 = require('../../../assets/public/theme/Screenshot_6.png');
const Screenshot_7 = require('../../../assets/public/theme/Screenshot_7.png');
import "../styles/_theme-selector.scss"; // Import SCSS

const themes = [
    { id: "theme-1", name: "Modern Purple [theme-1]", img: Screenshot_1 },
    { id: "theme-2", name: "Fresh Green [theme-2]", img: Screenshot_2 },
    { id: "theme-3", name: "Dark Contrast [theme-3]", img: Screenshot_3 },
    { id: "theme-4", name: "Modern Minimalist [theme-4]", img: Screenshot_4 },
    { id: "theme-5", name: "Futuristic Neon [theme-5]", img: Screenshot_5 },
    { id: "theme-6", name: "Neomorphic Light [theme-6]", img: Screenshot_6 },
    { id: "theme-7", name: "Glassmorphism Dark [theme-7]", img: Screenshot_7 },
];

const ThemeSelector = ({ selectedTheme, setSelectedTheme, customThemes = [], onEditTheme, onRefreshThemes, setNoticeModal }) => {
    const [deletingTheme, setDeletingTheme] = useState(null);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [themeToDelete, setThemeToDelete] = useState(null);
    const isProUser = isPro();
    
    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    // Combine default themes with custom themes
    const allThemes = [
        ...themes,
        ...customThemes.map(theme => ({
            id: theme.theme_id, // Use theme_id from database
            // name: `${theme.name} [${theme.theme_id}]`, // Show theme_id like preset themes
            name: `${theme.name}`, // Show simple name no id shows for custom theme
            img: theme.preview_image || Screenshot_1, // Use default image if no preview
            isCustom: true,
            themeData: theme.theme_data || theme,
            originalTheme: theme // Keep reference to original theme data
        }))
    ];

    const handleDeleteClick = (themeId, event) => {
        event.stopPropagation();
        setThemeToDelete(themeId);
        setShowDeleteModal(true);
    };

    const handleDeleteConfirm = async () => {
        if (!themeToDelete) return;

        setDeletingTheme(themeToDelete);

        try {
            const response = await fetch(getAjaxUrl(), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'simpleform_delete_custom_theme',
                    nonce: getNonce(),
                    theme_id: themeToDelete
                })
            });

            const data = await response.json();
            if (data.success) {
                // If the deleted theme was selected, reset to default
                if (selectedTheme === themeToDelete) {
                    setSelectedTheme('theme-1');
                }
                
                // Show success toast
                if (setNoticeModal) {
                    setNoticeModal({
                        isOpen: true,
                        type: 'toast',
                        mode: 'success',
                        title: 'Success',
                        message: 'Custom theme deleted successfully!',
                        position: 'top-right',
                        autoClose: true
                    });
                }
                
                // Refresh the theme list instead of reloading the page
                if (onRefreshThemes) {
                    onRefreshThemes();
                } else {
                    window.location.reload();
                }
            } else {
                if (setNoticeModal) {
                    setNoticeModal({
                        isOpen: true,
                        type: 'toast',
                        mode: 'error',
                        title: 'Error',
                        message: 'Error deleting theme: ' + (data.data?.message || 'Unknown error'),
                        position: 'top-right',
                        autoClose: true
                    });
                }
            }
        } catch (error) {
            console.error('Error deleting custom theme:', error);
            if (setNoticeModal) {
                setNoticeModal({
                    isOpen: true,
                    type: 'toast',
                    mode: 'error',
                    title: 'Error',
                    message: 'Error deleting theme. Please try again.',
                    position: 'top-right',
                    autoClose: true
                });
            }
        } finally {
            setDeletingTheme(null);
            setThemeToDelete(null);
        }
    };

    const handleEditCustomTheme = (theme, event) => {
        event.stopPropagation();
        
        if (onEditTheme) {
            onEditTheme(theme);
        } else {
            alert('Edit functionality not available');
        }
    };

    const handleThemeClick = (theme, themeIndex) => {
        // Check if theme is locked for free users
        if (!isProUser && isThemeLocked(themeIndex)) {
            const themeLockConfig = getThemeLockModalConfig();
            setModalConfig({
                ...themeLockConfig,
                onConfirm: () => {
                    window.open('https://wpazleen.com/', '_blank');
                    closeModal();
                },
                onClose: closeModal,
                confirmText: 'Upgrade to Pro',
                declineText: 'Maybe Later'
            });
            return;
        }
        
        setSelectedTheme(theme.id);
    };

    return (
        <>
            <div className="theme-selector">
                {allThemes.map((theme, index) => {
                    const isLocked = !isProUser && isThemeLocked(index);
                    
                    return (
                        <div
                            key={theme.id}
                            className={`theme-item ${selectedTheme === theme.id ? "active" : ""} ${theme.isCustom ? "custom-theme" : ""} ${isLocked ? "locked-theme" : ""}`}
                            onClick={() => handleThemeClick(theme, index)}
                            title={isLocked ? "Premium Theme - Upgrade to unlock" : theme.name}
                        >
                            <img src={theme.img} alt={theme.name} className={isLocked ? "blurred" : ""} />
                            <span>{theme.name}</span>
                            
                            {isLocked && (
                                <div className="theme-lock-overlay">
                                    <span className="pro-badge">🔒 PRO</span>
                                </div>
                            )}
                            
                            {theme.isCustom && !isLocked && (
                                <div className="custom-theme-actions">
                                    <button
                                        className="edit-custom-theme"
                                        onClick={(e) => handleEditCustomTheme(theme, e)}
                                        title="Edit custom theme"
                                        disabled={deletingTheme === theme.id}
                                    >
                                        ✏️
                                    </button>
                                    <button
                                        className="delete-custom-theme"
                                        onClick={(e) => handleDeleteClick(theme.id, e)}
                                        title="Delete custom theme"
                                        disabled={deletingTheme === theme.id}
                                    >
                                        {deletingTheme === theme.id ? '⏳' : '×'}
                                    </button>
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>

            <ConfirmModal
                isOpen={showDeleteModal}
                onClose={() => {
                    setShowDeleteModal(false);
                    setThemeToDelete(null);
                }}
                onConfirm={handleDeleteConfirm}
                title="Delete Custom Theme"
                message="Are you sure you want to delete this custom theme? This action cannot be undone and will permanently remove the theme from your collection."
                confirmText="Delete Theme"
                cancelText="Cancel"
                type="danger"
            />

            <NoticeModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position || 'center'}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />
        </>
    );
};

export default ThemeSelector;
