import { useState, useEffect, useRef } from 'react';
import './NomenclatureEntryForm.css';

// Auto-select text on focus (PF99 pattern)
const handleAutoSelect = (e) => e.target.select();
const preventDrag = (e) => e.preventDefault();

export default function NomenclatureEntryForm({
    fields = [],
    mode = 'add',
    initialData = null,
    onSave,
    onCancel,
    isSaving = false,
}) {
    const firstInputRef = useRef(null);
    const [formData, setFormData] = useState({});
    const [errors, setErrors] = useState({});

    // Initialize form data
    useEffect(() => {
        const data = {};
        const sortedFields = [...fields].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));

        for (const field of sortedFields) {
            if (mode === 'edit' && initialData) {
                data[field.key] = initialData[field.key] ?? getDefaultValue(field.field_type);
            } else {
                data[field.key] = getDefaultValue(field.field_type);
            }
        }
        setFormData(data);
        setErrors({});

        // Auto-focus first input
        setTimeout(() => firstInputRef.current?.focus(), 50);
    }, [fields, mode, initialData]);

    const getDefaultValue = (fieldType) => {
        switch (fieldType) {
            case 'bool': return false;
            case 'number': return '';
            case 'choice': return '';
            default: return '';
        }
    };

    const handleChange = (key, value) => {
        setFormData(prev => ({ ...prev, [key]: value }));
        // Clear error on change
        if (errors[key]) {
            setErrors(prev => ({ ...prev, [key]: null }));
        }
    };

    const validate = () => {
        const newErrors = {};
        const sortedFields = [...fields].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));

        for (const field of sortedFields) {
            if (field.required) {
                const val = formData[field.key];
                if (field.field_type === 'bool') continue; // booleans are always valid
                if (val === '' || val === null || val === undefined) {
                    newErrors[field.key] = `${field.label || field.key} is required`;
                }
            }
        }
        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!validate()) return;

        // Convert types before saving
        const cleanData = {};
        for (const field of fields) {
            let val = formData[field.key];
            if (field.field_type === 'number' && val !== '' && val !== undefined) {
                val = Number(val);
            }
            cleanData[field.key] = val;
        }
        onSave(cleanData);
    };

    const sortedFields = [...fields].sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));

    return (
        <form className="nui-entry-form" onSubmit={handleSubmit}>
            {sortedFields.map((field, idx) => (
                <div key={field.key} className="nui-entry-form-field">
                    <label>{field.label || field.key}{field.required ? ' *' : ''}</label>

                    {field.field_type === 'bool' ? (
                        <label className="nui-entry-form-checkbox-label">
                            <input
                                ref={idx === 0 ? firstInputRef : undefined}
                                type="checkbox"
                                checked={formData[field.key] || false}
                                onChange={(e) => handleChange(field.key, e.target.checked)}
                                disabled={isSaving}
                                className="nui-entry-form-checkbox"
                            />
                            <span>{formData[field.key] ? 'Yes' : 'No'}</span>
                        </label>
                    ) : field.field_type === 'number' ? (
                        <input
                            ref={idx === 0 ? firstInputRef : undefined}
                            type="number"
                            value={formData[field.key] ?? ''}
                            onChange={(e) => handleChange(field.key, e.target.value)}
                            onFocus={handleAutoSelect}
                            onDragStart={preventDrag}
                            disabled={isSaving}
                            className={errors[field.key] ? 'nui-entry-form-input-error' : ''}
                        />
                    ) : field.field_type === 'choice' && field.choices ? (
                        <select
                            ref={idx === 0 ? firstInputRef : undefined}
                            value={formData[field.key] || ''}
                            onChange={(e) => handleChange(field.key, e.target.value)}
                            disabled={isSaving}
                            className={errors[field.key] ? 'nui-entry-form-input-error' : ''}
                        >
                            <option value="">-- Select --</option>
                            {field.choices.map(c => (
                                <option key={c} value={c}>{c}</option>
                            ))}
                        </select>
                    ) : (
                        <input
                            ref={idx === 0 ? firstInputRef : undefined}
                            type="text"
                            value={formData[field.key] || ''}
                            onChange={(e) => handleChange(field.key, e.target.value)}
                            onFocus={handleAutoSelect}
                            onDragStart={preventDrag}
                            disabled={isSaving}
                            className={errors[field.key] ? 'nui-entry-form-input-error' : ''}
                        />
                    )}

                    {errors[field.key] && (
                        <span className="nui-entry-form-error">{errors[field.key]}</span>
                    )}
                </div>
            ))}

            <div className="nui-entry-form-actions">
                <button
                    type="button"
                    className="nui-entry-form-cancel"
                    onClick={onCancel}
                    disabled={isSaving}
                >
                    Cancel
                </button>
                <button
                    type="submit"
                    className="nui-entry-form-save"
                    disabled={isSaving}
                >
                    {isSaving ? 'Saving...' : mode === 'edit' ? 'Update' : 'Save'}
                </button>
            </div>
        </form>
    );
}
