import { useState } from '@wordpress/element';
import { Button, CheckboxControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { saveAutomation } from '../utils/api';

const StepSix = ({ formData, updateFormData, forms, fields, triggerChoices, mailjetLists, editId }) => {
    const [saving, setSaving] = useState(false);

    const handleSave = async (activate) => {
        setSaving(true);
        updateFormData('activate', activate);
        
        try {
            const result = await saveAutomation({ ...formData, activate }, editId);
            alert(__('Automation saved successfully!', 'wpforms-mailjet-automation'));
            window.location.href = 'admin.php?page=wpfmj-dashboard';
        } catch (error) {
            alert(__('Error saving automation: ', 'wpforms-mailjet-automation') + error.message);
        } finally {
            setSaving(false);
        }
    };

    const getFormName = () => {
        const form = forms.find(f => f.id.toString() === formData.form_id);
        return form ? form.title : formData.form_id;
    };

    const getFieldName = (fieldId) => {
        const field = fields.find(f => f.id.toString() === fieldId);
        return field ? field.label : fieldId;
    };

    const getTriggerFieldName = () => {
        return getFieldName(formData.trigger_field_id);
    };

    const getListName = (listId) => {
        const list = mailjetLists.find(l => l.id.toString() === listId);
        return list ? list.name : listId;
    };

    const getChoiceLabel = (choiceValue) => {
        const choice = triggerChoices.find(c => c.value === choiceValue);
        return choice ? choice.label : choiceValue;
    };

    return (
        <div className="wpfmj-step">
            <h2>{__('Review & Save', 'wpforms-mailjet-automation')}</h2>
            <p className="description">
                {__('Review your automation settings below. Once you\'re happy with everything, choose whether to save as a draft or save and activate immediately.', 'wpforms-mailjet-automation')}
            </p>

            <div className="wpfmj-review-section">
                <h3>{__('Basic Information', 'wpforms-mailjet-automation')}</h3>
                <div className="wpfmj-review-item">
                    <div className="wpfmj-review-label">{__('Automation Title:', 'wpforms-mailjet-automation')}</div>
                    <div className="wpfmj-review-value">{formData.title}</div>
                </div>
                <div className="wpfmj-review-item">
                    <div className="wpfmj-review-label">{__('Form:', 'wpforms-mailjet-automation')}</div>
                    <div className="wpfmj-review-value">{getFormName()}</div>
                </div>
            </div>

            <div className="wpfmj-review-section">
                <h3>{__('Field Mapping', 'wpforms-mailjet-automation')}</h3>
                <div className="wpfmj-review-item">
                    <div className="wpfmj-review-label">{__('Email Field:', 'wpforms-mailjet-automation')}</div>
                    <div className="wpfmj-review-value">{getFieldName(formData.field_mapping.email)}</div>
                </div>
                {formData.field_mapping.firstname && (
                    <div className="wpfmj-review-item">
                        <div className="wpfmj-review-label">{__('First Name Field:', 'wpforms-mailjet-automation')}</div>
                        <div className="wpfmj-review-value">{getFieldName(formData.field_mapping.firstname)}</div>
                    </div>
                )}
                {formData.field_mapping.lastname && (
                    <div className="wpfmj-review-item">
                        <div className="wpfmj-review-label">{__('Last Name Field:', 'wpforms-mailjet-automation')}</div>
                        <div className="wpfmj-review-value">{getFieldName(formData.field_mapping.lastname)}</div>
                    </div>
                )}
                <div className="wpfmj-review-item">
                    <div className="wpfmj-review-label">{__('Trigger Field:', 'wpforms-mailjet-automation')}</div>
                    <div className="wpfmj-review-value">{getTriggerFieldName()}</div>
                </div>
            </div>

            <div className="wpfmj-review-section">
                <h3>{__('List Mappings', 'wpforms-mailjet-automation')}</h3>
                {Object.entries(formData.list_mappings).map(([choiceValue, listId]) => (
                    <div key={choiceValue} className="wpfmj-review-item">
                        <div className="wpfmj-review-label">{getChoiceLabel(choiceValue)}:</div>
                        <div className="wpfmj-review-value">{getListName(listId)}</div>
                    </div>
                ))}
            </div>

            <div className="wpfmj-alert wpfmj-alert-info">
                <strong>{__('What happens next?', 'wpforms-mailjet-automation')}</strong>
                <ul style={{ margin: '10px 0 0 20px' }}>
                    <li>{__('When someone submits the selected form, the automation will check their answers', 'wpforms-mailjet-automation')}</li>
                    <li>{__('Based on their selections in the trigger field, they\'ll be added to the corresponding Mailjet list(s)', 'wpforms-mailjet-automation')}</li>
                    <li>{__('If the API call fails, the system will retry up to 3 times with exponential backoff', 'wpforms-mailjet-automation')}</li>
                    <li>{__('If all retries fail, you\'ll receive an email notification', 'wpforms-mailjet-automation')}</li>
                    <li>{__('You can view all automation activity and errors in the dashboard', 'wpforms-mailjet-automation')}</li>
                </ul>
            </div>

            <div style={{ marginTop: '30px', display: 'flex', gap: '10px' }}>
                <Button
                    variant="secondary"
                    onClick={() => handleSave(false)}
                    isBusy={saving}
                    disabled={saving}
                >
                    {__('Save as Draft', 'wpforms-mailjet-automation')}
                </Button>
                <Button
                    variant="primary"
                    onClick={() => handleSave(true)}
                    isBusy={saving}
                    disabled={saving}
                >
                    {__('Save & Activate', 'wpforms-mailjet-automation')}
                </Button>
            </div>
        </div>
    );
};

export default StepSix;
