/**
 * @file AdminConsole.tsx
 * @notice Admin console for bridge operations
 */

import { useState, useEffect } from 'react';

interface BridgeMetrics {
    totalTransfers: number;
    successRate: number;
    avgSettlementTime: number;
    refundRate: number;
    liquidityFailures: number;
}

interface Transfer {
    transferId: string;
    status: string;
    depositor: string;
    amount: string;
    destinationType: number;
    timestamp: number;
}

export default function AdminConsole() {
    const [metrics, setMetrics] = useState<BridgeMetrics | null>(null);
    const [transfers, setTransfers] = useState<Transfer[]>([]);
    const [searchId, setSearchId] = useState('');

    useEffect(() => {
        fetchMetrics();
        fetchRecentTransfers();
    }, []);

    const fetchMetrics = async () => {
        try {
            const response = await fetch('/api/admin/metrics');
            if (response.ok) {
                const data = await response.json();
                setMetrics(data);
            }
        } catch (error) {
            console.error('Failed to fetch metrics:', error);
        }
    };

    const fetchRecentTransfers = async () => {
        try {
            const response = await fetch('/api/admin/transfers?limit=50');
            if (response.ok) {
                const data = await response.json();
                setTransfers(data);
            }
        } catch (error) {
            console.error('Failed to fetch transfers:', error);
        }
    };

    const handlePause = async (type: 'global' | 'token' | 'destination', id?: string) => {
        try {
            const response = await fetch('/api/admin/pause', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type, id })
            });

            if (response.ok) {
                alert('Pause operation successful');
            } else {
                throw new Error('Pause failed');
            }
        } catch (error: any) {
            alert(`Error: ${error.message}`);
        }
    };

    const handleRefund = async (transferId: string) => {
        if (!confirm(`Initiate refund for transfer ${transferId}?`)) {
            return;
        }

        try {
            const response = await fetch(`/api/admin/refund/${transferId}`, {
                method: 'POST'
            });

            if (response.ok) {
                alert('Refund initiated');
                fetchRecentTransfers();
            } else {
                throw new Error('Refund failed');
            }
        } catch (error: any) {
            alert(`Error: ${error.message}`);
        }
    };

    return (
        <div className="container mx-auto px-4 py-8">
            <h1 className="text-3xl font-bold mb-6">Admin Console</h1>

            {/* Metrics Dashboard */}
            {metrics && (
                <div className="grid grid-cols-1 md:grid-cols-5 gap-4 mb-8">
                    <div className="p-4 bg-white rounded-lg shadow">
                        <div className="text-sm text-gray-600">Total Transfers</div>
                        <div className="text-2xl font-bold">{metrics.totalTransfers}</div>
                    </div>
                    <div className="p-4 bg-white rounded-lg shadow">
                        <div className="text-sm text-gray-600">Success Rate</div>
                        <div className="text-2xl font-bold">{metrics.successRate.toFixed(2)}%</div>
                    </div>
                    <div className="p-4 bg-white rounded-lg shadow">
                        <div className="text-sm text-gray-600">Avg Settlement</div>
                        <div className="text-2xl font-bold">{metrics.avgSettlementTime}s</div>
                    </div>
                    <div className="p-4 bg-white rounded-lg shadow">
                        <div className="text-sm text-gray-600">Refund Rate</div>
                        <div className="text-2xl font-bold">{metrics.refundRate.toFixed(2)}%</div>
                    </div>
                    <div className="p-4 bg-white rounded-lg shadow">
                        <div className="text-sm text-gray-600">Liquidity Failures</div>
                        <div className="text-2xl font-bold">{metrics.liquidityFailures}</div>
                    </div>
                </div>
            )}

            {/* Controls */}
            <div className="mb-8 p-4 bg-white rounded-lg shadow">
                <h2 className="text-xl font-bold mb-4">Controls</h2>
                <div className="flex gap-4">
                    <button
                        onClick={() => handlePause('global')}
                        className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
                    >
                        Pause Global
                    </button>
                    <button
                        onClick={() => handlePause('global')}
                        className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                    >
                        Resume Global
                    </button>
                </div>
            </div>

            {/* Transfer Search */}
            <div className="mb-8 p-4 bg-white rounded-lg shadow">
                <h2 className="text-xl font-bold mb-4">Search Transfer</h2>
                <div className="flex gap-2">
                    <input
                        type="text"
                        value={searchId}
                        onChange={(e) => setSearchId(e.target.value)}
                        placeholder="Enter transfer ID"
                        className="flex-1 p-2 border rounded"
                    />
                    <button
                        onClick={() => {
                            if (searchId) {
                                window.location.href = `/bridge?track=${searchId}`;
                            }
                        }}
                        className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                    >
                        Search
                    </button>
                </div>
            </div>

            {/* Recent Transfers */}
            <div className="p-4 bg-white rounded-lg shadow">
                <h2 className="text-xl font-bold mb-4">Recent Transfers</h2>
                <div className="overflow-x-auto">
                    <table className="w-full">
                        <thead>
                            <tr className="border-b">
                                <th className="text-left p-2">Transfer ID</th>
                                <th className="text-left p-2">Status</th>
                                <th className="text-left p-2">Amount</th>
                                <th className="text-left p-2">Destination</th>
                                <th className="text-left p-2">Time</th>
                                <th className="text-left p-2">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {transfers.map((transfer) => (
                                <tr key={transfer.transferId} className="border-b">
                                    <td className="p-2 font-mono text-sm">{transfer.transferId.slice(0, 16)}...</td>
                                    <td className="p-2">
                                        <span className={`px-2 py-1 rounded text-xs ${
                                            transfer.status === 'COMPLETED' ? 'bg-green-200' :
                                            transfer.status === 'FAILED' ? 'bg-red-200' :
                                            'bg-yellow-200'
                                        }`}>
                                            {transfer.status}
                                        </span>
                                    </td>
                                    <td className="p-2">{transfer.amount}</td>
                                    <td className="p-2">
                                        {transfer.destinationType === 0 ? 'EVM' :
                                         transfer.destinationType === 1 ? 'XRPL' : 'Fabric'}
                                    </td>
                                    <td className="p-2 text-sm">
                                        {new Date(transfer.timestamp * 1000).toLocaleString()}
                                    </td>
                                    <td className="p-2">
                                        {transfer.status === 'FAILED' && (
                                            <button
                                                onClick={() => handleRefund(transfer.transferId)}
                                                className="px-2 py-1 bg-orange-600 text-white rounded text-xs hover:bg-orange-700"
                                            >
                                                Refund
                                            </button>
                                        )}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
}
