/**
 * Admin Deposit Management Components
 * To be integrated into dashboard.html
 */

// Deposit Management Component
const AdminDeposits = () => {
    const [deposits, setDeposits] = React.useState([]);
    const [stats, setStats] = React.useState(null);
    const [loading, setLoading] = React.useState(true);
    const [filter, setFilter] = React.useState({
        status: '',
        payment_method: '',
        page: 1,
        limit: 20
    });
    const [selectedDeposit, setSelectedDeposit] = React.useState(null);
    const [showApproveModal, setShowApproveModal] = React.useState(false);
    const [showRejectModal, setShowRejectModal] = React.useState(false);
    const [adminNote, setAdminNote] = React.useState('');
    const [processing, setProcessing] = React.useState(false);

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

    // Load deposits
    const loadDeposits = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('token');
            const params = new URLSearchParams(filter);

            const response = await fetch(`${API_BASE_URL}/admin/deposits?${params}`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

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

    // Load statistics
    const loadStats = async () => {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_BASE_URL}/admin/deposits/stats`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                const data = await response.json();
                setStats(data.data);
            }
        } catch (error) {
            console.error('Error loading stats:', error);
        }
    };

    // Approve deposit
    const approveDeposit = async () => {
        setProcessing(true);
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_BASE_URL}/admin/deposits/${selectedDeposit.id}/approve`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ admin_note: adminNote })
            });

            if (response.ok) {
                alert('Deposit approved successfully!');
                setShowApproveModal(false);
                setAdminNote('');
                loadDeposits();
                loadStats();
            } else {
                const error = await response.json();
                alert('Failed to approve deposit: ' + error.message);
            }
        } catch (error) {
            console.error('Error approving deposit:', error);
            alert('Failed to approve deposit');
        } finally {
            setProcessing(false);
        }
    };

    // Reject deposit
    const rejectDeposit = async () => {
        if (!adminNote.trim()) {
            alert('Please provide a reason for rejection');
            return;
        }

        setProcessing(true);
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`${API_BASE_URL}/admin/deposits/${selectedDeposit.id}/reject`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ admin_note: adminNote })
            });

            if (response.ok) {
                alert('Deposit rejected successfully!');
                setShowRejectModal(false);
                setAdminNote('');
                loadDeposits();
                loadStats();
            } else {
                const error = await response.json();
                alert('Failed to reject deposit: ' + error.message);
            }
        } catch (error) {
            console.error('Error rejecting deposit:', error);
            alert('Failed to reject deposit');
        } finally {
            setProcessing(false);
        }
    };

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

    // Get status badge color
    const getStatusColor = (status) => {
        const colors = {
            'completed': 'bg-green-100 text-green-800',
            'pending': 'bg-yellow-100 text-yellow-800',
            'awaiting_payment': 'bg-blue-100 text-blue-800',
            'awaiting_proof': 'bg-purple-100 text-purple-800',
            'verifying': 'bg-blue-100 text-blue-800',
            'processing': 'bg-blue-100 text-blue-800',
            'failed': 'bg-red-100 text-red-800',
            'rejected': 'bg-red-100 text-red-800',
            'expired': 'bg-gray-100 text-gray-800'
        };
        return colors[status] || 'bg-gray-100 text-gray-800';
    };

    return (
        <div className="p-6">
            {/* Page Header */}
            <div className="mb-6">
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Deposit Management</h1>
                <p className="text-gray-600 dark:text-gray-400">Manage user deposits and payment approvals</p>
            </div>

            {/* Statistics Cards */}
            {stats && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                    <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-600 dark:text-gray-400">Total Deposits</p>
                                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                                    {stats.overall.total_deposits}
                                </p>
                            </div>
                            <div className="w-12 h-12 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center">
                                <i className="fas fa-list text-blue-600 dark:text-blue-400 text-xl"></i>
                            </div>
                        </div>
                    </div>

                    <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-600 dark:text-gray-400">Completed</p>
                                <p className="text-2xl font-bold text-green-600">
                                    {stats.overall.completed_deposits}
                                </p>
                            </div>
                            <div className="w-12 h-12 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
                                <i className="fas fa-check-circle text-green-600 dark:text-green-400 text-xl"></i>
                            </div>
                        </div>
                    </div>

                    <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-600 dark:text-gray-400">Pending Approval</p>
                                <p className="text-2xl font-bold text-yellow-600">
                                    {stats.overall.awaiting_proof_deposits}
                                </p>
                            </div>
                            <div className="w-12 h-12 bg-yellow-100 dark:bg-yellow-900 rounded-full flex items-center justify-center">
                                <i className="fas fa-clock text-yellow-600 dark:text-yellow-400 text-xl"></i>
                            </div>
                        </div>
                    </div>

                    <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-600 dark:text-gray-400">Total Amount</p>
                                <p className="text-2xl font-bold text-gray-900 dark:text-white">
                                    ₦{parseFloat(stats.overall.total_amount || 0).toLocaleString('en-NG', {minimumFractionDigits: 2})}
                                </p>
                            </div>
                            <div className="w-12 h-12 bg-purple-100 dark:bg-purple-900 rounded-full flex items-center justify-center">
                                <i className="fas fa-dollar-sign text-purple-600 dark:text-purple-400 text-xl"></i>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Filters */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Status
                        </label>
                        <select
                            value={filter.status}
                            onChange={(e) => setFilter({...filter, status: e.target.value, page: 1})}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                        >
                            <option value="">All Statuses</option>
                            <option value="pending">Pending</option>
                            <option value="awaiting_payment">Awaiting Payment</option>
                            <option value="awaiting_proof">Awaiting Proof</option>
                            <option value="verifying">Verifying</option>
                            <option value="processing">Processing</option>
                            <option value="completed">Completed</option>
                            <option value="failed">Failed</option>
                            <option value="rejected">Rejected</option>
                            <option value="expired">Expired</option>
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Payment Method
                        </label>
                        <select
                            value={filter.payment_method}
                            onChange={(e) => setFilter({...filter, payment_method: e.target.value, page: 1})}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                        >
                            <option value="">All Methods</option>
                            <option value="kuda">Kuda Bank</option>
                            <option value="opay">Opay</option>
                            <option value="moniepoint">Moniepoint</option>
                            <option value="palmpay">PalmPay</option>
                            <option value="binance">Binance Pay</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="ussd">USSD</option>
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Per Page
                        </label>
                        <select
                            value={filter.limit}
                            onChange={(e) => setFilter({...filter, limit: parseInt(e.target.value), page: 1})}
                            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white"
                        >
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                </div>
            </div>

            {/* Deposits Table */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
                {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 deposits...</p>
                    </div>
                ) : deposits.length === 0 ? (
                    <div className="text-center py-12">
                        <i className="fas fa-inbox text-4xl text-gray-400 mb-4"></i>
                        <p className="text-gray-600 dark:text-gray-400">No deposits found</p>
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                            <thead className="bg-gray-50 dark:bg-gray-700">
                                <tr>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        Reference
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        User
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        Payment Method
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        Amount
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        Status
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        Date
                                    </th>
                                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                        Actions
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                {deposits.map((deposit) => (
                                    <tr key={deposit.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
                                            {deposit.reference}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="text-sm font-medium text-gray-900 dark:text-white">
                                                {deposit.user_username || deposit.user_email}
                                            </div>
                                            <div className="text-sm text-gray-500 dark:text-gray-400">
                                                {deposit.first_name} {deposit.last_name}
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                                            {deposit.payment_method_name}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <div className="text-sm font-medium text-gray-900 dark:text-white">
                                                ₦{parseFloat(deposit.amount).toLocaleString('en-NG', {minimumFractionDigits: 2})}
                                            </div>
                                            <div className="text-xs text-gray-500 dark:text-gray-400">
                                                Fee: ₦{parseFloat(deposit.fee || 0).toLocaleString('en-NG', {minimumFractionDigits: 2})}
                                            </div>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap">
                                            <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(deposit.status)}`}>
                                                {deposit.status}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                                            {new Date(deposit.created_at).toLocaleString()}
                                        </td>
                                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            {deposit.status === 'awaiting_proof' && (
                                                <div className="flex space-x-2">
                                                    <button
                                                        onClick={() => {
                                                            setSelectedDeposit(deposit);
                                                            setShowApproveModal(true);
                                                        }}
                                                        className="text-green-600 hover:text-green-900"
                                                    >
                                                        <i className="fas fa-check"></i> Approve
                                                    </button>
                                                    <button
                                                        onClick={() => {
                                                            setSelectedDeposit(deposit);
                                                            setShowRejectModal(true);
                                                        }}
                                                        className="text-red-600 hover:text-red-900"
                                                    >
                                                        <i className="fas fa-times"></i> Reject
                                                    </button>
                                                </div>
                                            )}
                                            {deposit.payment_proof_url && (
                                                <a
                                                    href={deposit.payment_proof_url}
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    className="text-blue-600 hover:text-blue-900"
                                                >
                                                    <i className="fas fa-file"></i> View Proof
                                                </a>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            {/* Approve Modal */}
            {showApproveModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4">
                        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
                            Approve Deposit
                        </h3>
                        <p className="text-gray-600 dark:text-gray-400 mb-4">
                            Are you sure you want to approve this deposit?
                        </p>
                        <div className="mb-4">
                            <p className="text-sm text-gray-700 dark:text-gray-300">
                                <strong>Amount:</strong> ₦{parseFloat(selectedDeposit.amount).toLocaleString()}
                            </p>
                            <p className="text-sm text-gray-700 dark:text-gray-300">
                                <strong>User:</strong> {selectedDeposit.user_email}
                            </p>
                        </div>
                        <div className="mb-4">
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Admin Note (Optional)
                            </label>
                            <textarea
                                value={adminNote}
                                onChange={(e) => setAdminNote(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="Add any notes about this approval..."
                            />
                        </div>
                        <div className="flex space-x-3">
                            <button
                                onClick={approveDeposit}
                                disabled={processing}
                                className="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
                            >
                                {processing ? 'Processing...' : 'Approve'}
                            </button>
                            <button
                                onClick={() => {
                                    setShowApproveModal(false);
                                    setAdminNote('');
                                }}
                                className="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Reject Modal */}
            {showRejectModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4">
                        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">
                            Reject Deposit
                        </h3>
                        <p className="text-gray-600 dark:text-gray-400 mb-4">
                            Are you sure you want to reject this deposit?
                        </p>
                        <div className="mb-4">
                            <p className="text-sm text-gray-700 dark:text-gray-300">
                                <strong>Amount:</strong> ₦{parseFloat(selectedDeposit.amount).toLocaleString()}
                            </p>
                            <p className="text-sm text-gray-700 dark:text-gray-300">
                                <strong>User:</strong> {selectedDeposit.user_email}
                            </p>
                        </div>
                        <div className="mb-4">
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Reason for Rejection <span className="text-red-600">*</span>
                            </label>
                            <textarea
                                value={adminNote}
                                onChange={(e) => setAdminNote(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="Please provide a reason for rejection..."
                                required
                            />
                        </div>
                        <div className="flex space-x-3">
                            <button
                                onClick={rejectDeposit}
                                disabled={processing || !adminNote.trim()}
                                className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50"
                            >
                                {processing ? 'Processing...' : 'Reject'}
                            </button>
                            <button
                                onClick={() => {
                                    setShowRejectModal(false);
                                    setAdminNote('');
                                }}
                                className="flex-1 px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

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