import React, { useState, useEffect } from "react";
import { getNonce, getAjaxUrl } from '../../Helpers';
import ThemeSelector from "../ThemeSelector";
import CustomThemeCreator from "../CustomThemeCreator";
import NoticeModal from '../NoticeModal/NoticeModal';

const ThemeTab = ({ selectedTheme, setSelectedTheme }) => {
    const [activeTab, setActiveTab] = useState(() => {
        // Load active tab from localStorage or default to 'existing'
        return localStorage.getItem('simpleform_theme_active_tab') || 'existing';
    });
    const [customThemes, setCustomThemes] = useState([]);
    const [loading, setLoading] = useState(false);
    const [editingTheme, setEditingTheme] = useState(null);
    const [noticeModal, setNoticeModal] = useState({ isOpen: false, type: 'toast', mode: 'success', message: '' });

    // Save active tab to localStorage whenever it changes
    const handleTabChange = (tabName) => {
        setActiveTab(tabName);
        localStorage.setItem('simpleform_theme_active_tab', tabName);

        // Clear editing state when switching to existing themes
        if (tabName === 'existing') {
            setEditingTheme(null);
        }
    };

    // Load custom themes on component mount
    useEffect(() => {
        loadCustomThemes();
    }, []);

    const loadCustomThemes = async () => {
        try {
            const response = await fetch(getAjaxUrl(), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'simpleform_get_custom_themes',
                    nonce: getNonce()
                })
            });

            const data = await response.json();
            if (data.success) {
                setCustomThemes(data.data.themes || []);
            }
        } catch (error) {
            console.error('Error loading custom themes:', error);
        }
    };

    const handleSaveCustomTheme = async (themeData) => {
        setLoading(true);
        try {
            const response = await fetch(getAjaxUrl(), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'simpleform_save_custom_theme',
                    nonce: getNonce(),
                    theme_data: JSON.stringify(themeData)
                })
            });

            const data = await response.json();
            if (data.success) {
                // Reload custom themes
                await loadCustomThemes();
                // Clear editing state
                setEditingTheme(null);
                // Switch to existing themes tab
                handleTabChange('existing');
                // Show success toast
                setNoticeModal({
                    isOpen: true,
                    type: 'toast',
                    mode: 'success',
                    title: 'Success',
                    message: data.data?.message || 'Custom theme saved successfully!',
                    position: 'top-right',
                    autoClose: true
                });
            } else {
                // Show error toast
                setNoticeModal({
                    isOpen: true,
                    type: 'toast',
                    mode: 'error',
                    title: 'Error',
                    message: 'Error saving theme: ' + (data.data?.message || 'Unknown error'),
                    position: 'top-right',
                    autoClose: true
                });
            }
        } catch (error) {
            console.error('Error saving custom theme:', error);
            // Show error toast
            setNoticeModal({
                isOpen: true,
                type: 'toast',
                mode: 'error',
                title: 'Error',
                message: 'Error saving theme. Please try again.',
                position: 'top-right',
                autoClose: true
            });
        } finally {
            setLoading(false);
        }
    };

    const handleEditTheme = (theme) => {
        // Set the theme to be edited
        setEditingTheme(theme);
        // Switch to custom theme creator tab with the theme data
        handleTabChange('custom');
    };

    return (
        <div className="form-theme">
            <h3>Choose Your Theme</h3>

            <p className="theme-description">
                Select your preferred form theme from the options below or create your own custom theme.
                <br /><br />
                <span className="tip-highlight">Pro Tip:</span> You can override this theme for individual forms using the shortcode parameter:
                <code className="code-example">[simple_form id="1" theme="theme-1"]</code>
                <span className="tip-highlight">Attribute: </span><span className="tip-theme-list">theme-1 to theme-7 or custom theme IDs</span> <br />
                If no theme is specified in the shortcode, your selected default theme will be applied automatically.
            </p>

            <div className="theme-tabs">
                <button
                    className={`theme-tab ${activeTab === 'existing' ? 'active' : ''}`}
                    onClick={() => handleTabChange('existing')}
                >
                    Existing Themes
                </button>
                <button
                    className={`theme-tab ${activeTab === 'custom' ? 'active' : ''}`}
                    onClick={() => handleTabChange('custom')}
                >
                    {editingTheme ? 'Edit Custom Theme' : 'Create Custom Theme'}
                </button>
            </div>

            <div className="theme-content">
                {activeTab === 'existing' ? (
                    <ThemeSelector
                        selectedTheme={selectedTheme}
                        setSelectedTheme={setSelectedTheme}
                        customThemes={customThemes}
                        onEditTheme={handleEditTheme}
                        onRefreshThemes={loadCustomThemes}
                        setNoticeModal={setNoticeModal}
                    />
                ) : (
                    <CustomThemeCreator
                        onSaveTheme={handleSaveCustomTheme}
                        existingThemes={customThemes}
                        loading={loading}
                        editingTheme={editingTheme}
                    />
                )}
            </div>

            <NoticeModal
                isOpen={noticeModal.isOpen}
                onClose={() => setNoticeModal({ ...noticeModal, isOpen: false })}
                type={noticeModal.type}
                mode={noticeModal.mode}
                title={noticeModal.title}
                message={noticeModal.message}
                position={noticeModal.position}
                autoClose={noticeModal.autoClose}
            />
        </div>
    );
};

export default ThemeTab;