import { SelectControl, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

const StepFive = ({ formData, updateFormData, triggerChoices, mailjetLists, nextStep }) => {
    
    const handleNext = () => {
        const hasMapping = Object.keys(formData.list_mappings).length > 0;
        if (!hasMapping) {
            alert(__('Please map at least one answer to a Mailjet list', 'wpforms-mailjet-automation'));
            return;
        }
        nextStep();
    };

    const updateListMapping = (choiceValue, listId) => {
        const newMappings = { ...formData.list_mappings };
        
        if (listId === '') {
            // Remove mapping if empty
            delete newMappings[choiceValue];
        } else {
            newMappings[choiceValue] = listId;
        }
        
        updateFormData('list_mappings', newMappings);
    };

    // Get list of already selected lists to prevent duplicates
    const getAvailableLists = (currentChoiceValue) => {
        const usedListIds = Object.entries(formData.list_mappings)
            .filter(([key]) => key !== currentChoiceValue)
            .map(([, listId]) => listId);
        
        return mailjetLists.filter(list => !usedListIds.includes(list.id.toString()));
    };

    const listOptions = (choiceValue) => {
        const available = getAvailableLists(choiceValue);
        return [
            { label: __('Select a list...', 'wpforms-mailjet-automation'), value: '' },
            ...available.map(list => ({
                label: list.name,
                value: list.id.toString()
            }))
        ];
    };

    return (
        <div className="wpfmj-step">
            <h2>{__('Map Answers to Mailjet Lists', 'wpforms-mailjet-automation')}</h2>
            <p className="description">
                {__('Map each answer from your trigger field to a Mailjet list. When someone selects an answer, they\'ll be added to the corresponding list. Each list can only be used once.', 'wpforms-mailjet-automation')}
            </p>

            <div className="wpfmj-two-column">
                <div className="wpfmj-column">
                    <h3>{__('Form Answers', 'wpforms-mailjet-automation')}</h3>
                    {triggerChoices.map((choice) => (
                        <div key={choice.value} className="wpfmj-mapping-row">
                            <div className="wpfmj-answer">{choice.label}</div>
                        </div>
                    ))}
                </div>

                <div className="wpfmj-column">
                    <h3>{__('Mailjet Lists', 'wpforms-mailjet-automation')}</h3>
                    {triggerChoices.map((choice) => (
                        <div key={choice.value} className="wpfmj-mapping-row">
                            <SelectControl
                                value={formData.list_mappings[choice.value] || ''}
                                options={listOptions(choice.value)}
                                onChange={(value) => updateListMapping(choice.value, value)}
                            />
                        </div>
                    ))}
                </div>
            </div>

            {mailjetLists.length === 0 && (
                <div className="wpfmj-alert wpfmj-alert-error">
                    {__('No Mailjet lists found. Please create lists in your Mailjet account first.', 'wpforms-mailjet-automation')}
                </div>
            )}

            <div className="wpfmj-alert wpfmj-alert-info" style={{ marginTop: '20px' }}>
                <strong>{__('Note:', 'wpforms-mailjet-automation')}</strong> {__('For checkbox fields, users can select multiple answers, and they will be added to multiple lists accordingly.', 'wpforms-mailjet-automation')}
            </div>

            <Button
                variant="primary"
                onClick={handleNext}
                disabled={mailjetLists.length === 0}
                style={{ marginTop: '20px' }}
            >
                {__('Next', 'wpforms-mailjet-automation')}
            </Button>
        </div>
    );
};

export default StepFive;
