import { useState, useEffect } from '@wordpress/element';
import { Button, Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import StepOne from './components/StepOne';
import StepTwo from './components/StepTwo';
import StepThree from './components/StepThree';
import StepFour from './components/StepFour';
import StepFive from './components/StepFive';
import StepSix from './components/StepSix';
import { fetchAutomation } from './utils/api';

const WizardApp = () => {
    const [currentStep, setCurrentStep] = useState(1);
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState({
        title: '',
        form_id: '',
        field_mapping: {
            email: '',
            firstname: '',
            lastname: ''
        },
        trigger_field_id: '',
        api_key: '',
        api_secret: '',
        list_mappings: {},
        activate: false
    });
    const [forms, setForms] = useState([]);
    const [fields, setFields] = useState([]);
    const [triggerChoices, setTriggerChoices] = useState([]);
    const [mailjetLists, setMailjetLists] = useState([]);

    const totalSteps = 6;
    const editId = window.wpfmjData?.editId || 0;

    // Load automation if editing
    useEffect(() => {
        if (!editId) {
            return;
        }

        let cancelled = false;
        setLoading(true);

        fetchAutomation(editId)
            .then(data => {
                if (!cancelled) {
                    setFormData({
                        title: data.title,
                        ...data.config,
                        activate: data.status === 'publish'
                    });
                }
            })
            .catch(error => {
                if (!cancelled) {
                    alert('Error loading automation: ' + error.message);
                }
            })
            .finally(() => {
                if (!cancelled) {
                    setLoading(false);
                }
            });

        return () => {
            cancelled = true;
        };
    }, [editId]);

    const updateFormData = (field, value) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const nextStep = () => {
        if (currentStep < totalSteps) {
            setCurrentStep(currentStep + 1);
        }
    };

    const prevStep = () => {
        if (currentStep > 1) {
            setCurrentStep(currentStep - 1);
        }
    };

    const renderStep = () => {
        const stepProps = {
            formData,
            updateFormData,
            forms,
            setForms,
            fields,
            setFields,
            triggerChoices,
            setTriggerChoices,
            mailjetLists,
            setMailjetLists,
            nextStep,
            setLoading
        };

        switch (currentStep) {
            case 1:
                return <StepOne {...stepProps} />;
            case 2:
                return <StepTwo {...stepProps} />;
            case 3:
                return <StepThree {...stepProps} />;
            case 4:
                return <StepFour {...stepProps} />;
            case 5:
                return <StepFive {...stepProps} />;
            case 6:
                return <StepSix {...stepProps} editId={editId} />;
            default:
                return null;
        }
    };

    const renderProgress = () => {
        const steps = [
            __('Choose Form', 'wpforms-mailjet-automation'),
            __('Map Fields', 'wpforms-mailjet-automation'),
            __('Trigger Field', 'wpforms-mailjet-automation'),
            __('Connect Mailjet', 'wpforms-mailjet-automation'),
            __('Map Lists', 'wpforms-mailjet-automation'),
            __('Review', 'wpforms-mailjet-automation')
        ];

        return (
            <ul className="wpfmj-wizard-progress">
                {steps.map((step, index) => {
                    const stepNumber = index + 1;
                    const isActive = currentStep === stepNumber;
                    const isCompleted = currentStep > stepNumber;
                    const className = isActive ? 'active' : isCompleted ? 'completed' : '';

                    return (
                        <li key={stepNumber} className={className}>
                            {step}
                        </li>
                    );
                })}
            </ul>
        );
    };

    if (loading) {
        return (
            <div style={{ padding: '40px', textAlign: 'center' }}>
                <Spinner />
                <p>{__('Loading...', 'wpforms-mailjet-automation')}</p>
            </div>
        );
    }

    return (
        <div className="wpfmj-wizard-container">
            <div className="wpfmj-wizard-header">
                {renderProgress()}
            </div>
            <div className="wpfmj-wizard-body">
                {renderStep()}
            </div>
            <div className="wpfmj-wizard-footer">
                <div>
                    {currentStep > 1 && (
                        <Button
                            variant="secondary"
                            onClick={prevStep}
                            disabled={loading}
                        >
                            {__('Previous', 'wpforms-mailjet-automation')}
                        </Button>
                    )}
                </div>
                <div>
                    {currentStep < totalSteps && (
                        <Button
                            variant="primary"
                            onClick={nextStep}
                            disabled={loading}
                        >
                            {__('Next', 'wpforms-mailjet-automation')}
                        </Button>
                    )}
                </div>
            </div>
        </div>
    );
};

// Mount the app
document.addEventListener('DOMContentLoaded', () => {
    const rootElement = document.getElementById('wpfmj-wizard-root');
    if (rootElement) {
        wp.element.render(<WizardApp />, rootElement);
    }
});

export default WizardApp;
