import React, { useState } from 'react';

const CustomFieldsManager = ({ customFields = [], onChange }) => {
    const [showAddModal, setShowAddModal] = useState(false);
    const [newField, setNewField] = useState({
        key: '',
        value: '',
        type: 'text',
        editable: false
    });

    const handleAddField = (e) => {
        e.preventDefault();

        if (!newField.key.trim()) {
            return;
        }

        // Check for duplicate keys
        if (customFields.some(f => f.key === newField.key)) {
            alert('A field with this key already exists');
            return;
        }

        onChange([...customFields, { ...newField, id: Date.now() }]);
        setNewField({ key: '', value: '', type: 'text', editable: false });
        setShowAddModal(false);
    };

    const handleUpdateField = (id, field, value) => {
        onChange(customFields.map(f =>
            f.id === id ? { ...f, [field]: value } : f
        ));
    };

    const handleRemoveField = (id) => {
        const filtered = customFields.filter(f => f.id !== id);
        console.log('Removing field with id:', id);
        console.log('Before filter:', customFields.length, 'fields');
        console.log('After filter:', filtered.length, 'fields');
        console.log('Filtered fields:', filtered);
        onChange(filtered);
    };

    const renderFieldInput = (field) => {
        switch (field.type) {
            case 'textarea':
                return (
                    <textarea
                        value={field.value}
                        onChange={(e) => handleUpdateField(field.id, 'value', e.target.value)}
                        rows="3"
                        placeholder="Enter value..."
                    />
                );
            case 'number':
                return (
                    <input
                        type="number"
                        value={field.value}
                        onChange={(e) => handleUpdateField(field.id, 'value', e.target.value)}
                        placeholder="Enter number..."
                    />
                );
            case 'date':
                return (
                    <input
                        type="date"
                        value={field.value}
                        onChange={(e) => handleUpdateField(field.id, 'value', e.target.value)}
                    />
                );
            case 'checkbox':
                return (
                    <label className="checkbox-label">
                        <input
                            type="checkbox"
                            checked={field.value === 'yes' || field.value === true}
                            onChange={(e) => handleUpdateField(field.id, 'value', e.target.checked ? 'yes' : 'no')}
                        />
                        <span>Enabled</span>
                    </label>
                );
            case 'text':
            default:
                return (
                    <input
                        type="text"
                        value={field.value}
                        onChange={(e) => handleUpdateField(field.id, 'value', e.target.value)}
                        placeholder="Enter value..."
                    />
                );
        }
    };

    return (
        <div className="custom-fields-manager">
            {customFields.length === 0 ? (
                <p style={{ color: '#6b7280', fontSize: '14px', marginBottom: '16px' }}>
                    No custom fields added yet. Custom fields allow you to add extra data to your products.
                </p>
            ) : (
                <div className="custom-fields-list">
                    {customFields.map(field => (
                        <div key={field.id} className="custom-field-item">
                            <div className="field-header">
                                <div className="field-info">
                                    <strong>{field.key}</strong>
                                    <span className="field-type-badge">{field.type}</span>
                                    {field.editable && (
                                        <span className="field-editable-badge" title="Customers can edit this field">
                                            ✏️ Editable
                                        </span>
                                    )}
                                </div>
                                <button
                                    type="button"
                                    className="btn-remove"
                                    onClick={() => handleRemoveField(field.id)}
                                    title="Remove field"
                                >
                                    ✕
                                </button>
                            </div>
                            <div className="field-options">
                                <label className="checkbox-label">
                                    <input
                                        type="checkbox"
                                        checked={field.editable || false}
                                        onChange={(e) => handleUpdateField(field.id, 'editable', e.target.checked)}
                                    />
                                    <span>Allow customers to edit before adding to cart</span>
                                </label>
                            </div>
                            <div className="field-value">
                                {renderFieldInput(field)}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            <button
                type="button"
                className="btn btn-secondary btn-sm"
                onClick={() => setShowAddModal(true)}
            >
                + Add Custom Field
            </button>

            {/* Add Custom Field Modal */}
            {showAddModal && (
                <div className="modal-overlay" onClick={() => setShowAddModal(false)}>
                    <div className="modal-content modal-sm" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Add Custom Field</h3>
                            <button
                                type="button"
                                className="modal-close"
                                onClick={() => setShowAddModal(false)}
                            >
                                ✕
                            </button>
                        </div>

                        <div className="modal-body">
                            <div className="form-group">
                                <label>Field Key *</label>
                                <input
                                    type="text"
                                    value={newField.key}
                                    onChange={(e) => setNewField(prev => ({
                                        ...prev,
                                        key: e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, '_')
                                    }))}
                                    placeholder="field_key"
                                    required
                                />
                                <p className="help-text">
                                    Use lowercase letters, numbers, underscores, and hyphens only
                                </p>
                            </div>

                            <div className="form-group">
                                <label>Field Type</label>
                                <select
                                    value={newField.type}
                                    onChange={(e) => setNewField(prev => ({
                                        ...prev,
                                        type: e.target.value
                                    }))}
                                >
                                    <option value="text">Text</option>
                                    <option value="textarea">Textarea</option>
                                    <option value="number">Number</option>
                                    <option value="date">Date</option>
                                    <option value="checkbox">Checkbox</option>
                                </select>
                            </div>

                            <div className="form-group">
                                <label>Default Value</label>
                                {newField.type === 'textarea' ? (
                                    <textarea
                                        value={newField.value}
                                        onChange={(e) => setNewField(prev => ({
                                            ...prev,
                                            value: e.target.value
                                        }))}
                                        rows="3"
                                        placeholder="Enter default value..."
                                    />
                                ) : newField.type === 'checkbox' ? (
                                    <label className="checkbox-label">
                                        <input
                                            type="checkbox"
                                            checked={newField.value === 'yes'}
                                            onChange={(e) => setNewField(prev => ({
                                                ...prev,
                                                value: e.target.checked ? 'yes' : 'no'
                                            }))}
                                        />
                                        <span>Enabled by default</span>
                                    </label>
                                ) : (
                                    <input
                                        type={newField.type === 'number' ? 'number' : newField.type === 'date' ? 'date' : 'text'}
                                        value={newField.value}
                                        onChange={(e) => setNewField(prev => ({
                                            ...prev,
                                            value: e.target.value
                                        }))}
                                        placeholder="Enter default value..."
                                    />
                                )}
                            </div>

                            <div className="form-group">
                                <label className="checkbox-label">
                                    <input
                                        type="checkbox"
                                        checked={newField.editable || false}
                                        onChange={(e) => setNewField(prev => ({
                                            ...prev,
                                            editable: e.target.checked
                                        }))}
                                    />
                                    <span>Allow customers to edit this field before adding to cart</span>
                                </label>
                                <p className="help-text">
                                    If enabled, customers will see an input field on the product page
                                </p>
                            </div>
                        </div>

                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-secondary"
                                onClick={() => setShowAddModal(false)}
                            >
                                Cancel
                            </button>
                            <button
                                type="button"
                                className="btn btn-primary"
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    handleAddField(e);
                                }}
                            >
                                Add Field
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default CustomFieldsManager;
