/**
 * Admin Payment Methods Management Component
 * To be integrated into dashboard.html
 */

const AdminPaymentMethods = () => {
    const [methods, setMethods] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [showEditModal, setShowEditModal] = React.useState(false);
    const [selectedMethod, setSelectedMethod] = React.useState(null);
    const [formData, setFormData] = React.useState({});
    const [processing, setProcessing] = React.useState(false);

    const API_BASE_URL = 'http://localhost:5000/api';

    // Load payment methods
    const loadPaymentMethods = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_BASE_URL}/admin/payment-methods`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                const data = await response.json();
                setMethods(data.data);
            }
        } catch (error) {
            console.error('Error loading payment methods:', error);
        } finally {
            setLoading(false);
        }
    };

    // Edit method
    const editMethod = (method) => {
        setSelectedMethod(method);
        setFormData({
            name: method.name,
            description: method.description,
            transaction_fee_percentage: method.transaction_fee_percentage,
            transaction_fee_fixed: method.transaction_fee_fixed,
            transaction_fee_cap: method.transaction_fee_cap,
            min_amount: method.min_amount,
            max_amount: method.max_amount,
            is_active: method.is_active,
            is_automated: method.is_automated,
            requires_proof: method.requires_proof,
            processing_time_minutes: method.processing_time_minutes,
            instructions: method.instructions,
            display_order: method.display_order
        });
        setShowEditModal(true);
    };

    // Update method
    const updateMethod = async (e) => {
        e.preventDefault();
        setProcessing(true);

        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_BASE_URL}/admin/payment-methods/${selectedMethod.id}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            if (response.ok) {
                alert('Payment method updated successfully!');
                setShowEditModal(false);
                loadPaymentMethods();
            } else {
                const error = await response.json();
                alert('Failed to update payment method: ' + error.message);
            }
        } catch (error) {
            console.error('Error updating payment method:', error);
            alert('Failed to update payment method');
        } finally {
            setProcessing(false);
        }
    };

    // Toggle method status
    const toggleStatus = async (method) => {
        if (!confirm(`Are you sure you want to ${method.is_active ? 'deactivate' : 'activate'} ${method.name}?`)) {
            return;
        }

        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_BASE_URL}/admin/payment-methods/${method.id}`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ...method,
                    is_active: !method.is_active
                })
            });

            if (response.ok) {
                loadPaymentMethods();
            } else {
                alert('Failed to update status');
            }
        } catch (error) {
            console.error('Error toggling status:', error);
            alert('Failed to update status');
        }
    };

    // Load data on mount
    React.useEffect(() => {
        loadPaymentMethods();
    }, []);

    return (
        <div className="p-6">
            {/* Page Header */}
            <div className="mb-6">
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Payment Methods</h1>
                <p className="text-gray-600 dark:text-gray-400">Configure payment methods and fees</p>
            </div>

            {/* Payment Methods Grid */}
            {loading ? (
                <div className="text-center py-12">
                    <i className="fas fa-spinner fa-spin text-4xl text-green-600 mb-4"></i>
                    <p className="text-gray-600 dark:text-gray-400">Loading payment methods...</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {methods.map((method) => (
                        <div key={method.id} className="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden">
                            {/* Method Header */}
                            <div className={`p-4 ${method.is_active ? 'bg-green-50 dark:bg-green-900' : 'bg-gray-50 dark:bg-gray-700'}`}>
                                <div className="flex items-center justify-between mb-2">
                                    <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                                        {method.name}
                                    </h3>
                                    <span className={`px-2 py-1 text-xs font-semibold rounded ${method.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                                        {method.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                </div>
                                <p className="text-sm text-gray-600 dark:text-gray-400">
                                    Code: <span className="font-mono">{method.code}</span>
                                </p>
                                <p className="text-sm text-gray-600 dark:text-gray-400">
                                    Type: {method.type}
                                </p>
                            </div>

                            {/* Method Details */}
                            <div className="p-4">
                                <div className="space-y-2 mb-4">
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600 dark:text-gray-400">Transaction Fee:</span>
                                        <span className="font-medium text-gray-900 dark:text-white">
                                            {method.transaction_fee_percentage}%
                                            {method.transaction_fee_fixed > 0 && ` + ₦${method.transaction_fee_fixed}`}
                                        </span>
                                    </div>
                                    {method.transaction_fee_cap && (
                                        <div className="flex justify-between text-sm">
                                            <span className="text-gray-600 dark:text-gray-400">Fee Cap:</span>
                                            <span className="font-medium text-gray-900 dark:text-white">
                                                ₦{method.transaction_fee_cap}
                                            </span>
                                        </div>
                                    )}
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600 dark:text-gray-400">Limits:</span>
                                        <span className="font-medium text-gray-900 dark:text-white">
                                            ₦{method.min_amount.toLocaleString()} - ₦{method.max_amount.toLocaleString()}
                                        </span>
                                    </div>
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600 dark:text-gray-400">Processing:</span>
                                        <span className="font-medium text-gray-900 dark:text-white">
                                            {method.processing_time_minutes === 0 ? 'Instant' : `~${method.processing_time_minutes} min`}
                                        </span>
                                    </div>
                                    <div className="flex justify-between text-sm">
                                        <span className="text-gray-600 dark:text-gray-400">Mode:</span>
                                        <span className={`px-2 py-0.5 text-xs rounded ${method.is_automated ? 'bg-blue-100 text-blue-800' : 'bg-yellow-100 text-yellow-800'}`}>
                                            {method.is_automated ? 'Automated' : 'Manual'}
                                        </span>
                                    </div>
                                </div>

                                {/* Statistics */}
                                <div className="border-t border-gray-200 dark:border-gray-700 pt-3 mb-4">
                                    <div className="grid grid-cols-2 gap-2 text-sm">
                                        <div className="text-center">
                                            <p className="text-gray-600 dark:text-gray-400 text-xs">Total Deposits</p>
                                            <p className="font-bold text-gray-900 dark:text-white">{method.total_deposits || 0}</p>
                                        </div>
                                        <div className="text-center">
                                            <p className="text-gray-600 dark:text-gray-400 text-xs">Successful</p>
                                            <p className="font-bold text-green-600">{method.successful_deposits || 0}</p>
                                        </div>
                                    </div>
                                    <div className="mt-2 text-center">
                                        <p className="text-gray-600 dark:text-gray-400 text-xs">Total Amount</p>
                                        <p className="font-bold text-gray-900 dark:text-white">
                                            ₦{parseFloat(method.total_amount || 0).toLocaleString('en-NG', {minimumFractionDigits: 2})}
                                        </p>
                                    </div>
                                </div>

                                {/* Actions */}
                                <div className="flex space-x-2">
                                    <button
                                        onClick={() => editMethod(method)}
                                        className="flex-1 px-3 py-2 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
                                    >
                                        <i className="fas fa-edit mr-1"></i> Edit
                                    </button>
                                    <button
                                        onClick={() => toggleStatus(method)}
                                        className={`flex-1 px-3 py-2 text-sm rounded ${method.is_active ? 'bg-red-600 hover:bg-red-700' : 'bg-green-600 hover:bg-green-700'} text-white`}
                                    >
                                        <i className={`fas ${method.is_active ? 'fa-ban' : 'fa-check'} mr-1`}></i>
                                        {method.is_active ? 'Deactivate' : 'Activate'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* Edit Modal */}
            {showEditModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 overflow-y-auto">
                    <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 my-8">
                        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
                            Edit Payment Method: {selectedMethod.name}
                        </h3>

                        <form onSubmit={updateMethod}>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                {/* Name */}
                                <div className="md:col-span-2">
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Name
                                    </label>
                                    <input
                                        type="text"
                                        value={formData.name}
                                        onChange={(e) => setFormData({...formData, name: e.target.value})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                        required
                                    />
                                </div>

                                {/* Description */}
                                <div className="md:col-span-2">
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Description
                                    </label>
                                    <textarea
                                        value={formData.description || ''}
                                        onChange={(e) => setFormData({...formData, description: e.target.value})}
                                        rows="2"
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                    />
                                </div>

                                {/* Transaction Fee Percentage */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Fee Percentage (%)
                                    </label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={formData.transaction_fee_percentage}
                                        onChange={(e) => setFormData({...formData, transaction_fee_percentage: parseFloat(e.target.value)})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                    />
                                </div>

                                {/* Transaction Fee Fixed */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Fixed Fee (₦)
                                    </label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={formData.transaction_fee_fixed}
                                        onChange={(e) => setFormData({...formData, transaction_fee_fixed: parseFloat(e.target.value)})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                    />
                                </div>

                                {/* Transaction Fee Cap */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Fee Cap (₦)
                                    </label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={formData.transaction_fee_cap || ''}
                                        onChange={(e) => setFormData({...formData, transaction_fee_cap: e.target.value ? parseFloat(e.target.value) : null})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                    />
                                </div>

                                {/* Processing Time */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Processing Time (minutes)
                                    </label>
                                    <input
                                        type="number"
                                        value={formData.processing_time_minutes}
                                        onChange={(e) => setFormData({...formData, processing_time_minutes: parseInt(e.target.value)})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                    />
                                </div>

                                {/* Min Amount */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Min Amount (₦)
                                    </label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={formData.min_amount}
                                        onChange={(e) => setFormData({...formData, min_amount: parseFloat(e.target.value)})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                        required
                                    />
                                </div>

                                {/* Max Amount */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Max Amount (₦)
                                    </label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={formData.max_amount}
                                        onChange={(e) => setFormData({...formData, max_amount: parseFloat(e.target.value)})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                        required
                                    />
                                </div>

                                {/* Display Order */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Display Order
                                    </label>
                                    <input
                                        type="number"
                                        value={formData.display_order}
                                        onChange={(e) => setFormData({...formData, display_order: parseInt(e.target.value)})}
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                    />
                                </div>

                                {/* Instructions */}
                                <div className="md:col-span-2">
                                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Instructions (for manual payments)
                                    </label>
                                    <textarea
                                        value={formData.instructions || ''}
                                        onChange={(e) => setFormData({...formData, instructions: e.target.value})}
                                        rows="3"
                                        className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                                        placeholder="Enter payment instructions for users..."
                                    />
                                </div>

                                {/* Checkboxes */}
                                <div className="md:col-span-2 space-y-2">
                                    <label className="flex items-center">
                                        <input
                                            type="checkbox"
                                            checked={formData.is_active}
                                            onChange={(e) => setFormData({...formData, is_active: e.target.checked})}
                                            className="mr-2"
                                        />
                                        <span className="text-sm text-gray-700 dark:text-gray-300">Active</span>
                                    </label>
                                    <label className="flex items-center">
                                        <input
                                            type="checkbox"
                                            checked={formData.is_automated}
                                            onChange={(e) => setFormData({...formData, is_automated: e.target.checked})}
                                            className="mr-2"
                                        />
                                        <span className="text-sm text-gray-700 dark:text-gray-300">Automated</span>
                                    </label>
                                    <label className="flex items-center">
                                        <input
                                            type="checkbox"
                                            checked={formData.requires_proof}
                                            onChange={(e) => setFormData({...formData, requires_proof: e.target.checked})}
                                            className="mr-2"
                                        />
                                        <span className="text-sm text-gray-700 dark:text-gray-300">Requires Proof</span>
                                    </label>
                                </div>
                            </div>

                            <div className="flex space-x-3">
                                <button
                                    type="submit"
                                    disabled={processing}
                                    className="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
                                >
                                    {processing ? 'Saving...' : 'Save Changes'}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setShowEditModal(false)}
                                    className="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
                                >
                                    Cancel
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

// Export for use in dashboard
window.AdminPaymentMethods = AdminPaymentMethods;
