/**
 * Form Canvas - Drop target for form fields
 */

import { __ } from '@wordpress/i18n';
import { Icon, plus } from '@wordpress/icons';
import { DEFAULT_FIELD_CONFIG, generateFieldId } from '../../config/fieldTypes';
import FormField from './FormField';
import './FormCanvas.css';

export default function FormCanvas({
    fields = [],
    selectedFieldId,
    onDrop,
    onSelectField,
    onUpdateField,
    onMoveField,
    onDeleteField,
}) {
    const handleDragOver = (event) => {
        event.preventDefault();
        event.dataTransfer.dropEffect = 'copy';
    };

    const handleDrop = (event) => {
        event.preventDefault();
        const fieldType = event.dataTransfer.getData('formipay-field-type');
        if (!fieldType) return;

        const newField = {
            ...DEFAULT_FIELD_CONFIG,
            field_type: fieldType,
            field_id: generateFieldId(fieldType.replace('_', ' ')),
            label: fieldType.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()),
        };

        onDrop?.(newField);
    };

    const handleReorder = (dragIndex, dropIndex) => {
        const newFields = [...fields];
        const [draggedField] = newFields.splice(dragIndex, 1);
        newFields.splice(dropIndex, 0, draggedField);
        onMoveField?.(newFields);
    };

    return (
        <div className="formipay-form-canvas">
            <div className="formipay-canvas-header">
                <h3>{ __('Form Fields', 'formipay') }</h3>
                <span className="field-count">
                    { fields.length } { __('fields', 'formipay') }
                </span>
            </div>

            <div
                className={`formipay-canvas-area ${fields.length === 0 ? 'is-empty' : ''}`}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
            >
                {fields.length === 0 ? (
                    <div className="formipay-empty-state">
                        <Icon icon={plus} size={48} />
                        <p>
                            { __('Drag fields from the palette to build your form', 'formipay') }
                        </p>
                    </div>
                ) : (
                    <div className="formipay-fields-list">
                        {fields.map((field, index) => (
                            <FormField
                                key={field.field_id}
                                field={field}
                                index={index}
                                isSelected={selectedFieldId === field.field_id}
                                onSelect={() => onSelectField?.(field.field_id)}
                                onUpdate={(updates) => onUpdateField?.(field.field_id, updates)}
                                onMoveUp={index > 0 ? () => handleReorder(index, index - 1) : null}
                                onMoveDown={index < fields.length - 1 ? () => handleReorder(index, index + 1) : null}
                                onDelete={() => onDeleteField?.(field.field_id)}
                                onDragStart={(e) => {
                                    e.dataTransfer.effectAllowed = 'move';
                                    e.dataTransfer.setData('formipay-field-index', index.toString());
                                }}
                                onDragOver={(e) => {
                                    e.preventDefault();
                                    e.dataTransfer.dropEffect = 'move';
                                }}
                                onDrop={(e) => {
                                    e.preventDefault();
                                    const fromIndex = parseInt(e.dataTransfer.getData('formipay-field-index'));
                                    if (!isNaN(fromIndex) && fromIndex !== index) {
                                        handleReorder(fromIndex, index);
                                    }
                                }}
                            />
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
