/**
 * Chain Management Dashboard
 * Admin UI for managing all supported chains, adapters, and deployments
 */

import { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import { useAccount } from 'wagmi';
import DashboardSection from '../../features/omnl-dashboard/DashboardSection';
import NasaIcon, { StatusIcon } from '../icons/NasaIcon';
import NasaPageHeader from '../../features/omnl-dashboard/NasaPageHeader';

interface ChainMetadata {
    chainId: number;
    chainIdentifier: string;
    chainType: string;
    adapter: string;
    isActive: boolean;
    explorerUrl: string;
    minConfirmations: number;
    avgBlockTime: number;
}

function getErrorMessage(error: unknown): string {
    return error instanceof Error ? error.message : 'Unknown error';
}

export default function ChainManagementDashboard() {
    const { address, isConnected } = useAccount();
    const [chains, setChains] = useState<ChainMetadata[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedChain, setSelectedChain] = useState<string>('');

    useEffect(() => {
        if (isConnected) {
            loadChains();
        }
    }, [isConnected, address]);

    const loadChains = async () => {
        try {
            setLoading(true);
            setChains([
                {
                    chainId: 138,
                    chainIdentifier: 'EVM-138',
                    chainType: 'EVM',
                    adapter: '0x...',
                    isActive: true,
                    explorerUrl: 'https://explorer.d-bis.org',
                    minConfirmations: 12,
                    avgBlockTime: 2
                },
                {
                    chainId: 50,
                    chainIdentifier: 'EVM-50',
                    chainType: 'XDC',
                    adapter: '0x...',
                    isActive: true,
                    explorerUrl: 'https://explorer.xdc.network',
                    minConfirmations: 12,
                    avgBlockTime: 2
                }
            ]);
        } catch (error: unknown) {
            toast.error(`Failed to load chains: ${getErrorMessage(error)}`);
        } finally {
            setLoading(false);
        }
    };

    const toggleChain = async (currentStatus: boolean) => {
        try {
            toast.success(`Chain ${currentStatus ? 'disabled' : 'enabled'}`);
            loadChains();
        } catch (error: unknown) {
            toast.error(`Failed to toggle chain: ${getErrorMessage(error)}`);
        }
    };

    if (!isConnected) {
        return (
            <div className="dash-card nasa-mission-root">
                <p className="text-[#7a9bb8] flex items-center gap-2">
                    <NasaIcon name="wallet" size={16} className="nasa-icon--telemetry" />
                    Please connect your wallet to manage chains.
                </p>
            </div>
        );
    }

    return (
        <div className="space-y-6 nasa-mission-root">
            <NasaPageHeader
                icon="network"
                missionId="NET-ADM"
                title="Chain Management"
                subtitle="Supported chains, adapters, and deployment registry"
            />

            <DashboardSection title="Registered chains" icon="globe">
                {loading ? (
                    <p className="text-[#7a9bb8] flex items-center gap-2">
                        <NasaIcon name="loading" size={14} className="nasa-icon--spin nasa-icon--telemetry" />
                        Loading chains…
                    </p>
                ) : (
                    <div className="space-y-4">
                        {chains.map((chain) => (
                            <div key={chain.chainId || chain.chainIdentifier} className="nasa-inset-panel flex items-center justify-between gap-4 flex-wrap">
                                <div>
                                    <h3 className="text-[#e8f4ff] font-semibold font-mono flex items-center gap-2">
                                        <NasaIcon name="network" size={14} className="nasa-icon--telemetry" />
                                        {chain.chainIdentifier} ({chain.chainType})
                                    </h3>
                                    <p className="text-[#7a9bb8] text-sm font-mono">Adapter: {chain.adapter.slice(0, 10)}…</p>
                                    <p className="text-[#7a9bb8] text-sm">
                                        Explorer:{' '}
                                        <a href={chain.explorerUrl} target="_blank" rel="noopener noreferrer" className="text-[#00d4ff] hover:underline inline-flex items-center gap-1">
                                            <NasaIcon name="link" size={12} />
                                            {chain.explorerUrl}
                                        </a>
                                    </p>
                                </div>
                                <div className="flex items-center gap-4">
                                    <span className={`nasa-badge flex items-center gap-1 ${chain.isActive ? 'nasa-badge--nominal' : 'nasa-badge--caution'}`}>
                                        <StatusIcon ok={chain.isActive} />
                                        {chain.isActive ? 'Active' : 'Inactive'}
                                    </span>
                                    <button
                                        onClick={() => toggleChain(chain.isActive)}
                                        className={`nasa-btn ${chain.isActive ? '' : 'nasa-btn--primary'}`}
                                    >
                                        {chain.isActive ? 'Disable' : 'Enable'}
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </DashboardSection>

            <DashboardSection title="Add new chain" icon="rocket">
                <div className="space-y-4">
                    <select
                        value={selectedChain}
                        onChange={(e) => setSelectedChain(e.target.value)}
                        className="nasa-select"
                    >
                        <option value="">Select chain to add…</option>
                        <option value="polygon">Polygon</option>
                        <option value="arbitrum">Arbitrum</option>
                        <option value="optimism">Optimism</option>
                        <option value="base">Base</option>
                        <option value="avalanche">Avalanche</option>
                        <option value="bsc">BSC</option>
                        <option value="ethereum">Ethereum Mainnet</option>
                    </select>
                    <button
                        onClick={() => toast('Deployment feature coming soon')}
                        className="nasa-btn nasa-btn--primary w-full"
                    >
                        <NasaIcon name="rocket" size={14} />
                        Deploy chain adapter
                    </button>
                </div>
            </DashboardSection>
        </div>
    );
}
