/**
 * Work Assignments Component v2
 * 
 * Clean implementation with:
 * - Array guards before all .map() calls
 * - Loading & empty states
 * - User-friendly error handling
 * - Debug logging
 */

const { useState, useEffect } = React;

// Debug logger
function debugLog(context, message, data = null) {
    if (window.WM_DEBUG_FIELDS) {
        console.log(`[WorkAssignments-v2] [${context}]`, message, data || '');
    }
}

// Work Assignments Component
function WorkAssignmentsV2() {
    const [assignments, setAssignments] = useState([]);
    const [fieldConfig, setFieldConfig] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showModal, setShowModal] = useState(false);
    const [selectedAssignment, setSelectedAssignment] = useState(null);
    const [showBin, setShowBin] = useState(false);
    const [toast, setToast] = useState(null);
    const [errorLogId, setErrorLogId] = useState(null);
    
    // Load field configuration
    useEffect(() => {
        loadFieldConfig();
    }, []);
    
    // Load assignments
    useEffect(() => {
        loadAssignments();
    }, [showBin]);
    
    const loadFieldConfig = async () => {
        debugLog('loadFieldConfig', 'Starting...');
        
        try {
            const response = await fetch(`${IWM_DATA.apiUrl}/work-manager/v1/work-assignments/fields`, {
                headers: {
                    'X-WP-Nonce': IWM_DATA.nonce
                }
            });
            
            const result = await response.json();
            debugLog('loadFieldConfig', 'Response:', result);
            
            if (result.success && result.data) {
                // CRITICAL: Guard to ensure array
                const fields = Array.isArray(result.data) ? result.data : [];
                debugLog('loadFieldConfig', 'Fields array length:', fields.length);
                
                setFieldConfig(fields);
            } else {
                throw new Error(result.message || 'Failed to load field configuration');
            }
        } catch (err) {
            debugLog('loadFieldConfig', 'ERROR:', err);
            handleError('Failed to load form configuration', err);
        }
    };
    
    const loadAssignments = async () => {
        debugLog('loadAssignments', 'Starting...', { showBin });
        setLoading(true);
        setError(null);
        
        try {
            const endpoint = showBin ? '/work-assignments/bin' : '/work-assignments';
            const response = await fetch(`${IWM_DATA.apiUrl}/work-manager/v1${endpoint}`, {
                headers: {
                    'X-WP-Nonce': IWM_DATA.nonce
                }
            });
            
            const result = await response.json();
            debugLog('loadAssignments', 'Response:', result);
            
            if (result.success && result.data) {
                // CRITICAL: Guard to ensure array
                const assignmentList = Array.isArray(result.data) ? result.data : [];
                debugLog('loadAssignments', 'Assignments array length:', assignmentList.length);
                
                setAssignments(assignmentList);
            } else {
                throw new Error(result.message || 'Failed to load assignments');
            }
        } catch (err) {
            debugLog('loadAssignments', 'ERROR:', err);
            handleError('Failed to load assignments', err);
        } finally {
            setLoading(false);
        }
    };
    
    const handleCreateAssignment = async (formData) => {
        debugLog('handleCreateAssignment', 'Data:', formData);
        
        try {
            const response = await fetch(`${IWM_DATA.apiUrl}/work-manager/v1/work-assignments`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': IWM_DATA.nonce
                },
                body: JSON.stringify(formData)
            });
            
            const result = await response.json();
            debugLog('handleCreateAssignment', 'Response:', result);
            
            if (result.success) {
                showToast('Assignment created successfully!', 'success');
                setShowModal(false);
                loadAssignments();
            } else {
                throw new Error(result.message || 'Failed to create assignment');
            }
        } catch (err) {
            debugLog('handleCreateAssignment', 'ERROR:', err);
            handleError('Failed to create assignment', err);
        }
    };
    
    const handleMoveToBin = async (id) => {
        debugLog('handleMoveToBin', 'ID:', id);
        
        try {
            const response = await fetch(`${IWM_DATA.apiUrl}/work-manager/v1/work-assignments/${id}/bin`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': IWM_DATA.nonce
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                showToast('Assignment moved to bin', 'success');
                loadAssignments();
            } else {
                throw new Error(result.message || 'Failed to move to bin');
            }
        } catch (err) {
            handleError('Failed to move to bin', err);
        }
    };
    
    const handleRestore = async (id) => {
        debugLog('handleRestore', 'ID:', id);
        
        try {
            const response = await fetch(`${IWM_DATA.apiUrl}/work-manager/v1/work-assignments/${id}/restore`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': IWM_DATA.nonce
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                showToast('Assignment restored', 'success');
                loadAssignments();
            } else {
                throw new Error(result.message || 'Failed to restore');
            }
        } catch (err) {
            handleError('Failed to restore assignment', err);
        }
    };
    
    const handleDelete = async (id) => {
        if (!confirm('Permanently delete this assignment? This action cannot be undone.')) {
            return;
        }
        
        debugLog('handleDelete', 'ID:', id);
        
        try {
            const response = await fetch(`${IWM_DATA.apiUrl}/work-manager/v1/work-assignments/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-WP-Nonce': IWM_DATA.nonce
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                showToast('Assignment permanently deleted', 'success');
                loadAssignments();
            } else {
                throw new Error(result.message || 'Failed to delete');
            }
        } catch (err) {
            handleError('Failed to delete assignment', err);
        }
    };
    
    const handleError = (userMessage, error) => {
        const logId = 'ERR_' + Date.now();
        console.error(`[${logId}]`, userMessage, error);
        
        setError({
            message: userMessage,
            details: error.message,
            logId: logId
        });
        setErrorLogId(logId);
    };
    
    const showToast = (message, type = 'success') => {
        setToast({ message, type });
        setTimeout(() => setToast(null), 3000);
    };
    
    // Loading state
    if (loading && assignments.length === 0) {
        return (
            <div style={{ textAlign: 'center', padding: '60px 20px' }}>
                <div style={{ fontSize: '48px', marginBottom: '20px' }}>⏳</div>
                <h3>Loading Work Assignments...</h3>
                <div className="wm-spinner" style={{
                    border: '4px solid #f3f3f3',
                    borderTop: '4px solid #0073aa',
                    borderRadius: '50%',
                    width: '40px',
                    height: '40px',
                    animation: 'spin 1s linear infinite',
                    margin: '20px auto'
                }}></div>
            </div>
        );
    }
    
    return (
        <div className="wm-work-assignments-v2">
            {/* Header */}
            <div className="wm-header">
                <h2>{showBin ? '🗑️ Bin' : '📋 Work Assignments'}</h2>
                <div className="wm-header-actions">
                    {!showBin && (
                        <button 
                            className="wm-btn wm-btn-primary" 
                            onClick={() => { setSelectedAssignment(null); setShowModal(true); }}
                        >
                            ➕ New Assignment
                        </button>
                    )}
                    <button 
                        className="wm-btn wm-btn-secondary" 
                        onClick={() => setShowBin(!showBin)}
                    >
                        {showBin ? '← Back to Assignments' : '🗑️ View Bin'}
                    </button>
                </div>
            </div>
            
            {/* Error Display */}
            {error && (
                <div className="wm-error-banner" style={{
                    background: '#fef7f1',
                    border: '2px solid #dc3232',
                    borderRadius: '8px',
                    padding: '20px',
                    margin: '20px 0'
                }}>
                    <h3 style={{ margin: '0 0 10px', color: '#dc3232' }}>⚠️ {error.message}</h3>
                    <p style={{ margin: '0 0 15px' }}>{error.details}</p>
                    <p style={{ fontSize: '12px', color: '#666' }}>
                        Error Log ID: <code>{error.logId}</code> (Check browser console for details)
                    </p>
                    <button 
                        className="wm-btn wm-btn-secondary" 
                        onClick={() => setError(null)}
                    >
                        Dismiss
                    </button>
                </div>
            )}
            
            {/* Empty state */}
            {!loading && assignments.length === 0 && (
                <div style={{ textAlign: 'center', padding: '60px 20px', background: '#f9f9f9', borderRadius: '8px' }}>
                    <div style={{ fontSize: '64px', marginBottom: '20px' }}>
                        {showBin ? '🗑️' : '📋'}
                    </div>
                    <h3>{showBin ? 'Bin is empty' : 'No assignments yet'}</h3>
                    <p style={{ color: '#666', marginBottom: '20px' }}>
                        {showBin 
                            ? 'Deleted assignments will appear here for 30 days before auto-deletion.' 
                            : 'Get started by creating your first assignment.'}
                    </p>
                    {!showBin && (
                        <button 
                            className="wm-btn wm-btn-primary" 
                            onClick={() => setShowModal(true)}
                        >
                            ➕ Create First Assignment
                        </button>
                    )}
                </div>
            )}
            
            {/* Assignments List */}
            {Array.isArray(assignments) && assignments.length > 0 && (
                <div className="wm-assignments-grid">
                    {assignments.map(assignment => (
                        <AssignmentCard 
                            key={assignment.id}
                            assignment={assignment}
                            isInBin={showBin}
                            onMoveToBin={handleMoveToBin}
                            onRestore={handleRestore}
                            onDelete={handleDelete}
                        />
                    ))}
                </div>
            )}
            
            {/* Create/Edit Modal */}
            {showModal && (
                <AssignmentModal
                    fieldConfig={fieldConfig}
                    assignment={selectedAssignment}
                    onClose={() => setShowModal(false)}
                    onSubmit={handleCreateAssignment}
                />
            )}
            
            {/* Toast Notification */}
            {toast && (
                <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />
            )}
        </div>
    );
}

// Assignment Card Component
function AssignmentCard({ assignment, isInBin, onMoveToBin, onRestore, onDelete }) {
    return (
        <div className="wm-assignment-card">
            <div className="wm-card-header">
                <h3>{assignment.title}</h3>
                <span className="wm-category-badge">{assignment.category}</span>
            </div>
            <div className="wm-card-body">
                {assignment.assignee_name && (
                    <p><strong>Assignee:</strong> {assignment.assignee_name}</p>
                )}
                {assignment.description && (
                    <p className="wm-description">{assignment.description}</p>
                )}
                <p className="wm-meta">
                    Created: {new Date(assignment.created_at).toLocaleDateString()}
                </p>
            </div>
            <div className="wm-card-actions">
                {!isInBin ? (
                    <>
                        <button className="wm-btn wm-btn-secondary" onClick={() => onMoveToBin(assignment.id)}>
                            🗑️ Move to Bin
                        </button>
                    </>
                ) : (
                    <>
                        <button className="wm-btn wm-btn-success" onClick={() => onRestore(assignment.id)}>
                            ↩️ Restore
                        </button>
                        <button className="wm-btn wm-btn-danger" onClick={() => onDelete(assignment.id)}>
                            🗑️ Delete Permanently
                        </button>
                    </>
                )}
            </div>
        </div>
    );
}

// Assignment Modal Component
function AssignmentModal({ fieldConfig, assignment, onClose, onSubmit }) {
    const [formData, setFormData] = useState(assignment || {});
    const [errors, setErrors] = useState({});
    
    // CRITICAL: Guard before mapping
    const fields = Array.isArray(fieldConfig) ? fieldConfig : [];
    
    debugLog('AssignmentModal', 'Field config:', { isArray: Array.isArray(fieldConfig), count: fields.length });
    
    const handleSubmit = (e) => {
        e.preventDefault();
        
        // Validate required fields
        const newErrors = {};
        fields.forEach(field => {
            if (field.required && field.enabled && !formData[field.key]) {
                newErrors[field.key] = `${field.label} is required`;
            }
        });
        
        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
            return;
        }
        
        onSubmit(formData);
    };
    
    const handleChange = (key, value) => {
        setFormData({ ...formData, [key]: value });
        if (errors[key]) {
            setErrors({ ...errors, [key]: null });
        }
    };
    
    return (
        <div className="wm-modal-overlay" onClick={onClose}>
            <div className="wm-modal-content" onClick={e => e.stopPropagation()}>
                <div className="wm-modal-header">
                    <h2>{assignment ? 'Edit Assignment' : 'New Assignment'}</h2>
                    <button className="wm-modal-close" onClick={onClose}>✕</button>
                </div>
                
                <form onSubmit={handleSubmit}>
                    <div className="wm-modal-body">
                        {fields.length === 0 ? (
                            <div style={{ padding: '20px', textAlign: 'center', background: '#fef7f1', borderRadius: '8px' }}>
                                <p>⚠️ No form fields configured. Please configure fields in the Dev Tools panel.</p>
                            </div>
                        ) : (
                            fields.map(field => (
                                field.enabled && (
                                    <div key={field.key} className="wm-form-group">
                                        <label>
                                            {field.label}
                                            {field.required && <span className="wm-required">*</span>}
                                        </label>
                                        {field.type === 'textarea' ? (
                                            <textarea
                                                value={formData[field.key] || ''}
                                                onChange={e => handleChange(field.key, e.target.value)}
                                                placeholder={field.placeholder}
                                                rows={4}
                                            />
                                        ) : field.type === 'select' ? (
                                            <select
                                                value={formData[field.key] || ''}
                                                onChange={e => handleChange(field.key, e.target.value)}
                                            >
                                                <option value="">{field.placeholder || 'Select...'}</option>
                                                {Array.isArray(field.options) && field.options.map(option => (
                                                    <option key={option} value={option}>{option}</option>
                                                ))}
                                            </select>
                                        ) : (
                                            <input
                                                type={field.type}
                                                value={formData[field.key] || ''}
                                                onChange={e => handleChange(field.key, e.target.value)}
                                                placeholder={field.placeholder}
                                            />
                                        )}
                                        {errors[field.key] && (
                                            <span className="wm-field-error">{errors[field.key]}</span>
                                        )}
                                    </div>
                                )
                            ))
                        )}
                    </div>
                    
                    <div className="wm-modal-footer">
                        <button type="button" className="wm-btn wm-btn-secondary" onClick={onClose}>
                            Cancel
                        </button>
                        <button type="submit" className="wm-btn wm-btn-primary" disabled={fields.length === 0}>
                            {assignment ? 'Update' : 'Create'} Assignment
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

// Toast Component
function Toast({ message, type, onClose }) {
    useEffect(() => {
        const timer = setTimeout(onClose, 3000);
        return () => clearTimeout(timer);
    }, [onClose]);
    
    const icon = type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️';
    const bgColor = type === 'success' ? '#46b450' : type === 'error' ? '#dc3232' : '#0073aa';
    
    return (
        <div style={{
            position: 'fixed',
            top: '20px',
            right: '20px',
            background: bgColor,
            color: 'white',
            padding: '15px 25px',
            borderRadius: '8px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
            zIndex: 10000,
            display: 'flex',
            alignItems: 'center',
            gap: '10px'
        }}>
            <span>{icon}</span>
            <span>{message}</span>
            <button onClick={onClose} style={{
                background: 'transparent',
                border: 'none',
                color: 'white',
                fontSize: '20px',
                cursor: 'pointer',
                padding: '0 0 0 10px'
            }}>×</button>
        </div>
    );
}

// Export for integration
window.WorkAssignmentsV2 = WorkAssignmentsV2;
