import React, { useState, useRef, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import settingsSchema from '../../../settings-schema.json';

import DirectoryBasics from './DirectoryBasics';
import DirectoryLayout from './DirectoryLayout';
import ProfileLayout from './ProfileLayout';
import ProfileContent from './ProfileContent';
import AdvancedControl from './AdvancedControl';
import DirectorySuccess from './DirectorySuccess';
import Toast from '../common/Toast';

// Build default values from settingsSchema
const DEFAULTS = Object.values(settingsSchema.panels).flatMap(panel => Object.values(panel.fields || {})).reduce((acc, setting) => {
    acc[setting.name] = setting.default;
    return acc;
}, {});

const DirectoryWizard = ({ onClose, initialData }) => {
    const [formData, setFormData] = useState({ ...DEFAULTS });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [toastMessage, setToastMessage] = useState(null);
    const [isDirty, setIsDirty] = useState(false);
    const [initialFormData, setInitialFormData] = useState({ ...DEFAULTS });

    // Custom setFormData wrapper that tracks dirty state
    const updateFormData = (updater, options = {}) => {
        const { skipDirtyCheck = false } = options;
        
        setFormData(prevData => {
            const newData = typeof updater === 'function' ? updater(prevData) : updater;
            
            // Check if form is dirty by comparing with initial data (only if not skipping)
            if (!skipDirtyCheck) {
                const isFormDirty = JSON.stringify(newData) !== JSON.stringify(initialFormData);
                setIsDirty(isFormDirty);
            }
            
            return newData;
        });
    };

    // Use local state for step navigation
    const baseSteps = [
        { id: 'basics', label: __('Directory Basics', 'wpuf-pro') },
        { id: 'layout', label: __('Directory Layout', 'wpuf-pro') },
        { id: 'profile', label: __('Profile Layout', 'wpuf-pro') },
        { id: 'content', label: __('Profile Content', 'wpuf-pro') },
        { id: 'advanced', label: __('Advanced Control', 'wpuf-pro') },
    ];
    
    // Only add success step when creating new directory
    const steps = initialData 
        ? baseSteps 
        : [...baseSteps, { id: 'success', label: __('Success', 'wpuf-pro') }];
    const [currentStepIndex, setCurrentStepIndex] = useState(0);
    const [fade, setFade] = useState(true);
    const prevStepIndex = useRef(0);

    useEffect(() => {
        if (initialData && initialData.post_content) {
            const parsedContent = JSON.parse(initialData.post_content || '{}');
            const newFormData = {
                ...DEFAULTS,
                directory_title: initialData.post_title || '',
                ...parsedContent,
                ID: initialData.ID,
                // Ensure orderby and order have defaults even if not in saved data
                orderby: parsedContent.orderby || DEFAULTS.orderby || 'id',
                order: parsedContent.order || DEFAULTS.order || 'desc',
                // Also set the UI fields for default sort
                default_sort_by: parsedContent.default_sort_by || parsedContent.orderby || DEFAULTS.orderby || 'id',
                default_sort_order: parsedContent.default_sort_order || parsedContent.order || DEFAULTS.order || 'desc',
                // Ensure max_item is a number
                max_item: parsedContent.max_item ? parseInt(parsedContent.max_item) : DEFAULTS.max_item,
                max_item_per_page: parsedContent.max_item_per_page ? parseInt(parsedContent.max_item_per_page) : DEFAULTS.max_item_per_page,
            };
            setFormData(newFormData);
            setInitialFormData(newFormData);
            setIsDirty(false); // Reset dirty state when loading initial data
        }
    }, [initialData]);


    // Add browser beforeunload event listener for unsaved changes
    useEffect(() => {
        const handleBeforeUnload = (e) => {
            if (isDirty) {
                e.preventDefault();
                e.returnValue = ''; // Chrome requires returnValue to be set
                return 'You have unsaved changes. Are you sure you want to leave?';
            }
        };

        window.addEventListener('beforeunload', handleBeforeUnload);

        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, [isDirty]);

    // Helper function to confirm navigation - only for leaving wizard
    const confirmLeavingWizard = (callback) => {
        if (isDirty) {
            const confirmed = window.confirm(__('You have unsaved changes. Are you sure you want to leave? Your changes will be lost.', 'wpuf-pro'));
            if (confirmed) {
                callback();
            }
        } else {
            callback();
        }
    };
    
    // Navigation between steps without warning
    const navigateToStep = (stepIndex) => {
        setFade(false);
        setTimeout(() => {
            prevStepIndex.current = currentStepIndex;
            setCurrentStepIndex(stepIndex);
            setFade(true);
        }, 200);
    };

    const handleNextStep = () => {
        // When editing (no success step), last step is at steps.length - 1
        // When creating (with success step), last step before success is at steps.length - 2
        const isLastStep = initialData 
            ? currentStepIndex === steps.length - 1
            : currentStepIndex === steps.length - 2;
            
        if (!isLastStep) {
            setFade(false);
            setTimeout(() => {
                prevStepIndex.current = currentStepIndex;
                setCurrentStepIndex(currentStepIndex + 1);
                setFade(true);
            }, 200);
        } else {
            handleSubmit();
        }
    };

    const handlePrevStep = () => {
        if (currentStepIndex > 0) {
            setFade(false);
            setTimeout(() => {
                prevStepIndex.current = currentStepIndex;
                setCurrentStepIndex(currentStepIndex - 1);
                setFade(true);
            }, 200);
        }
    };

    const handleSubmit = async () => {
        setLoading(true);
        setError('');
        
        try {
            let response;
            if (formData.ID) {
                // Editing existing directory
                response = await fetch(`/wp-json/wpuf/v1/user_directory/${formData.ID}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                    },
                    body: JSON.stringify(formData),
                });
            } else {
                // Creating new directory
                response = await fetch('/wp-json/wpuf/v1/user_directory', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                    },
                    body: JSON.stringify(formData),
                });
            }
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.message || __('Something went wrong', 'wpuf-pro'));
            }
            setToastMessage({ text: __('Directory settings saved successfully!', 'wpuf-pro'), type: 'success' });
            setIsDirty(false); // Reset dirty state after successful save
            setInitialFormData(formData); // Update initial data after save
            setLoading(false);
            setTimeout(() => {
                if (formData.ID) {
                    // If editing, go directly to the list page
                    onClose();
                } else {
                    // If creating new, show success page
                    setCurrentStepIndex(steps.length - 1); // Go to success step
                }
            }, 1500);
        } catch (err) {
            setError(err.message || __('Something went wrong', 'wpuf-pro'));
            setLoading(false);
        }
    };

    const handleSaveAndExit = async () => {
        setLoading(true);
        setError('');
        try {
            let response;
            if (formData.ID) {
                // Editing existing directory
                response = await fetch(`/wp-json/wpuf/v1/user_directory/${formData.ID}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                    },
                    body: JSON.stringify(formData),
                });
            } else {
                // Creating new directory
                response = await fetch('/wp-json/wpuf/v1/user_directory', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                    },
                    body: JSON.stringify(formData),
                });
            }
            if (!response.ok) {
                const data = await response.json();
                throw new Error(data.message || __('Something went wrong', 'wpuf-pro'));
            }
            setToastMessage({ text: __('Directory settings saved successfully!', 'wpuf-pro'), type: 'success' });
            setIsDirty(false); // Reset dirty state after successful save
            setInitialFormData(formData); // Update initial data after save
            setLoading(false);
            setTimeout(() => {
                onClose(); // Return to the list
            }, 1500);
        } catch (err) {
            setError(err.message || __('Something went wrong', 'wpuf-pro'));
            setLoading(false);
        }
    };

    // Render the current step component
    let StepComponent;
    switch (currentStepIndex) {
        case 0:
            StepComponent = <DirectoryBasics formData={formData} setFormData={updateFormData} />;
            break;
        case 1:
            StepComponent = <DirectoryLayout formData={formData} setFormData={updateFormData} />;
            break;
        case 2:
            StepComponent = <ProfileLayout formData={formData} setFormData={updateFormData} />;
            break;
        case 3:
            StepComponent = <ProfileContent formData={formData} setFormData={updateFormData} isEditing={!!initialData} />;
            break;
        case 4:
            StepComponent = <AdvancedControl formData={formData} setFormData={updateFormData} />;
            break;
        case 5:
            // Only show success step when creating new directory
            if (!initialData) {
                StepComponent = <DirectorySuccess onClose={onClose} />;
            }
            break;
        default:
            StepComponent = null;
    }

    return (
        <div className="wpuf-directory-wizard wpuf-w-full wpuf-pb-24">
            <div className="wpuf-flex wpuf-justify-between wpuf-m-8">
                <a href="#" onClick={(e) => { e.preventDefault(); confirmLeavingWizard(onClose); }} className="wpuf-flex wpuf-items-center wpuf-text-gray-500 hover:wpuf-text-gray-700">
                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" className="wpuf-mr-1">
                        <path d="M15.8332 10.0001H4.1665M4.1665 10.0001L9.99984 15.8334M4.1665 10.0001L9.99984 4.16675" stroke="currentColor" strokeWidth="1.67" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                    <span className="wpuf-text-gray-700 wpuf-text-base wpuf-font-medium">{__('Directory List', 'wpuf-pro')}</span>
                </a>

                {
                    // Show Save and Exit on all steps except the Success page (only when creating new)
                    // When editing, show on all steps. When creating, hide only on success page
                    (initialData || (!initialData && currentStepIndex < steps.length - 1)) && (
                        <button
                            onClick={handleSaveAndExit}
                            className="wpuf-btn-white wpuf-flex wpuf-items-center"
                            disabled={loading}
                        >
                            {loading && (
                                <span className="wpuf-animate-spin wpuf-mr-2 wpuf-inline-block wpuf-w-4 wpuf-h-4 wpuf-border-2 wpuf-border-gray-600 wpuf-border-t-transparent wpuf-rounded-full"></span>
                            )}
                            { loading ? __( 'Saving...', 'wpuf-pro' ) : __( 'Save and Exit', 'wpuf-pro' ) }
                        </button>
                    )
                }
            </div>

            {(initialData || currentStepIndex !== steps.length - 1) && (
                <div className="wpuf-flex wpuf-justify-center">
                    <div className="wpuf-w-2/3 wpuf-max-w-2/3">
                        <p className="wpuf-text-center" style={{  fontWeight: 400, fontSize: '30px', lineHeight: '36px', letterSpacing: '0%' }}>{__( 'Set up your Directory', 'wpuf-pro' )}</p>

                            <nav aria-label="Progress" className="wpuf-flex wpuf-justify-center wpuf-mt-10">
                                <ol role="list" className="wpuf-flex wpuf-items-center">
                                    {steps.slice(0, initialData ? steps.length : steps.length - 1).map( ( step, index ) => (
                                        <li key={step.id} className="wpuf-relative wpuf-list-none">
                                            <div className={`wpuf-relative ${index !== (initialData ? steps.length - 1 : steps.length - 2) ? 'wpuf-pr-40' : '' }`}>
                                                {( index !== (initialData ? steps.length - 1 : steps.length - 2) ) && (
                                                <div className="wpuf-absolute wpuf-inset-0 wpuf-flex wpuf-items-center"
                                                     aria-hidden="true">
                                                    <div
                                                        className={`wpuf-h-0.5 wpuf-w-full ${index < currentStepIndex ? 'wpuf-bg-emerald-600' : 'wpuf-bg-gray-200'}`}></div>
                                                </div>
                                                )}
                                                <a href="#"
                                                     className={`wpuf-relative wpuf-flex wpuf-items-center wpuf-justify-center focus:wpuf-shadow-none ${index <= currentStepIndex ? '' : 'wpuf-border-2 wpuf-border-gray-300 wpuf-bg-white hover:wpuf-border-gray-400'}`}
                                                     style={{ 
                                                         width: '24px', 
                                                         height: '24px', 
                                                         borderRadius: '23px',
                                                         opacity: 1,
                                                         backgroundColor: index <= currentStepIndex ? '#059669' : ''
                                                     }}
                                                     onClick={e => { e.preventDefault(); navigateToStep(index); }}>
                                                    <svg width="9" height="7" viewBox="0 0 9 7" fill="none" xmlns="http://www.w3.org/2000/svg"
                                                         aria-hidden="true">
                                                        <path d="M1 3.4001L3.4 5.8001L7.6 1.6001" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                                    </svg>
                                                </a>
                                                <span 
                                                    className="wpuf-w-max wpuf-absolute wpuf-left-[-35px] wpuf-top-8 wpuf-flex wpuf-items-center wpuf-justify-center"
                                                    style={{ 
                                                        
                                                        fontWeight: 400,
                                                        fontSize: '14px',
                                                        lineHeight: '20px',
                                                        letterSpacing: '0%',
                                                        textAlign: 'center',
                                                        color: index <= currentStepIndex ? '#059669' : '#374151'
                                                    }}
                                                >{step.label}</span>
                                            </div>
                                        </li>
                                    ) )}
                                </ol>
                            </nav>
                    </div>
                </div>
            )}

            <div className="wpuf-mt-16 wpuf-mx-auto wpuf-w-full">
                <div
                    key={currentStepIndex}
                    className={`wpuf-flex wpuf-flex-col wpuf-justify-center wpuf-transition-opacity wpuf-duration-200 wpuf-ease-in-out ${fade ? 'wpuf-opacity-100' : 'wpuf-opacity-0'}`}
                >
                    {error && (
                        <div className="wpuf-mb-4 wpuf-text-red-600 wpuf-bg-red-50 wpuf-p-2 wpuf-rounded">
                            {error}
                        </div>
                    )}
                    {StepComponent}
                </div>
            </div>

            {/* Sticky Bottom Navigation - Hide only on success page when creating new */}
            {(initialData || currentStepIndex !== steps.length - 1) && (
                <div className="wpuf-fixed wpuf-bottom-0 !wpuf-bg-white wpuf-border-t wpuf-border-gray-200 wpuf-shadow-lg wpuf-z-50" 
                     style={{ 
                         left: document.body.classList.contains('folded') ? '36px' : '160px', 
                         right: '0' 
                     }}>
                    <div className="wpuf-container wpuf-mx-auto">
                        <div className="wpuf-flex wpuf-justify-between wpuf-items-center wpuf-max-w-4xl wpuf-mx-auto wpuf-py-4">
                        {/* Left side buttons */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-3 wpuf-ml-0">
                            {/* Cancel button - only show on first step */}
                            {currentStepIndex === 0 && (
                                <button
                                    onClick={() => confirmLeavingWizard(onClose)}
                                    className="wpuf-px-4 wpuf-py-2 wpuf-text-gray-700 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md hover:wpuf-bg-gray-50 focus:wpuf-outline-none focus:wpuf-ring-2 focus:wpuf-ring-offset-2 focus:wpuf-ring-gray-500 wpuf-transition-colors"
                                >
                                    {__( 'Cancel', 'wpuf-pro' )}
                                </button>
                            )}
                            
                            {/* Previous button - show after first step */}
                            {currentStepIndex > 0 && (initialData || currentStepIndex < steps.length - 1) && (
                                <button
                                    onClick={handlePrevStep}
                                    className="wpuf-px-4 wpuf-py-2 wpuf-text-gray-700 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md hover:wpuf-bg-gray-50 focus:wpuf-outline-none focus:wpuf-ring-2 focus:wpuf-ring-offset-2 focus:wpuf-ring-gray-500 wpuf-transition-colors wpuf-flex wpuf-items-center"
                                >
                                    <svg className="wpuf-w-4 wpuf-h-4 wpuf-mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                    </svg>
                                    {__( 'Previous', 'wpuf-pro' )}
                                </button>
                            )}
                        </div>

                        {/* Right side buttons */}
                        <div className="wpuf-flex wpuf-items-center wpuf-ml-0">
                            {/* Next/Submit button */}
                            {(initialData || currentStepIndex < steps.length - 1) && (
                                <button
                                    onClick={handleNextStep}
                                    className="wpuf-px-6 wpuf-py-2 wpuf-text-white wpuf-bg-emerald-600 wpuf-rounded-md hover:wpuf-bg-emerald-700 focus:wpuf-outline-none focus:wpuf-ring-2 focus:wpuf-ring-offset-2 focus:wpuf-ring-emerald-500 wpuf-transition-colors wpuf-flex wpuf-items-center disabled:wpuf-opacity-50 disabled:wpuf-cursor-not-allowed"
                                    disabled={loading}
                                >
                                    {loading && (initialData ? currentStepIndex === steps.length - 1 : currentStepIndex === steps.length - 2) && (
                                        <span className="wpuf-animate-spin wpuf-mr-2 wpuf-inline-block wpuf-w-4 wpuf-h-4 wpuf-border-2 wpuf-border-white wpuf-border-t-transparent wpuf-rounded-full"></span>
                                    )}
                                    {(initialData ? currentStepIndex === steps.length - 1 : currentStepIndex === steps.length - 2) 
                                        ? (loading ? __( 'Saving...', 'wpuf-pro' ) : __( 'Save Changes', 'wpuf-pro' ))
                                        : __( 'Next', 'wpuf-pro' )}
                                    {!loading && !(initialData ? currentStepIndex === steps.length - 1 : currentStepIndex === steps.length - 2) && (
                                        <svg className="wpuf-w-4 wpuf-h-4 wpuf-ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                        </svg>
                                    )}
                                </button>
                            )}
                        </div>
                        </div>
                    </div>
                </div>
            )}
            {toastMessage && (
                <Toast 
                    message={toastMessage.text} 
                    type={toastMessage.type} 
                    onClose={() => setToastMessage(null)}
                />
            )}
        </div>
    );
};

export default DirectoryWizard;
