import { useEffect, useState } from 'react';
import {
  Server,
  Wifi,
  WifiOff,
  Users,
  Blocks,
  RefreshCw,
  Power,
  PowerOff,
  Globe,
  HardDrive,
} from 'lucide-react';
import { useNodeStore, ConnectionMode } from '../../store/node';

export default function NodeDashboard() {
  const {
    status,
    syncProgress,
    peers,
    preferredMode,
    lastExternalUrl,
    lastNetwork,
    connectExternal,
    startEmbeddedNode,
    disconnect,
    refreshStatus,
    refreshPeers,
    setupEventListeners,
    cleanupEventListeners,
  } = useNodeStore();

  const [isConnecting, setIsConnecting] = useState(false);
  const [externalUrl, setExternalUrl] = useState(lastExternalUrl);
  const [embeddedNetwork, setEmbeddedNetwork] = useState(lastNetwork);
  const [error, setError] = useState<string | null>(null);

  // Setup event listeners on mount
  useEffect(() => {
    setupEventListeners();
    return () => cleanupEventListeners();
  }, [setupEventListeners, cleanupEventListeners]);

  // Refresh status periodically when connected
  useEffect(() => {
    if (!status.isConnected) return;

    const interval = setInterval(() => {
      refreshStatus();
      refreshPeers();
    }, 5000);

    return () => clearInterval(interval);
  }, [status.isConnected, refreshStatus, refreshPeers]);

  const handleConnectExternal = async () => {
    setIsConnecting(true);
    setError(null);
    try {
      await connectExternal(externalUrl);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Connection failed');
    } finally {
      setIsConnecting(false);
    }
  };

  const handleStartEmbedded = async () => {
    setIsConnecting(true);
    setError(null);
    try {
      await startEmbeddedNode({ network: embeddedNetwork });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to start node');
    } finally {
      setIsConnecting(false);
    }
  };

  const handleDisconnect = async () => {
    setError(null);
    try {
      await disconnect();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Disconnect failed');
    }
  };

  const getModeLabel = (mode: ConnectionMode): string => {
    switch (mode.type) {
      case 'disconnected':
        return 'Disconnected';
      case 'external':
        return `External: ${mode.http_url}`;
      case 'embedded':
        return `Embedded: ${mode.network}`;
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Server size={28} />
            Node
          </h1>
          <p className="text-gray-400 mt-1">
            Manage your connection to the Synor network
          </p>
        </div>

        {status.isConnected && (
          <button
            onClick={handleDisconnect}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-600 hover:bg-red-700 text-white transition-colors"
          >
            <PowerOff size={18} />
            Disconnect
          </button>
        )}
      </div>

      {/* Error display */}
      {error && (
        <div className="p-4 rounded-lg bg-red-900/30 border border-red-800 text-red-400">
          {error}
        </div>
      )}

      {/* Connection Status Card */}
      <div className="p-6 rounded-xl bg-gray-900 border border-gray-800">
        <div className="flex items-center gap-4">
          {status.isConnected ? (
            <div className="p-3 rounded-full bg-green-500/20">
              <Wifi size={24} className="text-green-400" />
            </div>
          ) : (
            <div className="p-3 rounded-full bg-gray-700">
              <WifiOff size={24} className="text-gray-400" />
            </div>
          )}
          <div>
            <h2 className="text-lg font-semibold text-white">
              {status.isConnected ? 'Connected' : 'Not Connected'}
            </h2>
            <p className="text-sm text-gray-400">{getModeLabel(status.mode)}</p>
          </div>
        </div>

        {/* Sync progress bar */}
        {status.isConnected && status.isSyncing && syncProgress && (
          <div className="mt-4">
            <div className="flex justify-between text-sm text-gray-400 mb-2">
              <span>Syncing...</span>
              <span>{syncProgress.progress.toFixed(1)}%</span>
            </div>
            <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
              <div
                className="h-full bg-synor-500 transition-all duration-300"
                style={{ width: `${syncProgress.progress}%` }}
              />
            </div>
            <p className="text-xs text-gray-500 mt-1">{syncProgress.status}</p>
          </div>
        )}
      </div>

      {/* Stats Grid (when connected) */}
      {status.isConnected && (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard
            icon={<Blocks size={20} />}
            label="Block Height"
            value={status.blockHeight.toLocaleString()}
          />
          <StatCard
            icon={<HardDrive size={20} />}
            label="Blue Score"
            value={status.blueScore.toLocaleString()}
          />
          <StatCard
            icon={<Users size={20} />}
            label="Peers"
            value={status.peerCount.toString()}
          />
          <StatCard
            icon={<Globe size={20} />}
            label="Network"
            value={status.network || 'Unknown'}
          />
        </div>
      )}

      {/* Connection Options (when disconnected) */}
      {!status.isConnected && (
        <div className="grid gap-6 md:grid-cols-2">
          {/* External Node */}
          <div className="p-6 rounded-xl bg-gray-900 border border-gray-800">
            <div className="flex items-center gap-3 mb-4">
              <Globe size={24} className="text-synor-400" />
              <h3 className="text-lg font-semibold text-white">External Node</h3>
            </div>
            <p className="text-sm text-gray-400 mb-4">
              Connect to a remote Synor node via RPC. No local resources required.
            </p>
            <div className="space-y-3">
              <input
                type="text"
                value={externalUrl}
                onChange={(e) => setExternalUrl(e.target.value)}
                placeholder="http://localhost:16110"
                className="w-full px-4 py-3 rounded-lg bg-gray-800 border border-gray-700 text-white placeholder-gray-500 focus:outline-none focus:border-synor-500"
              />
              <button
                onClick={handleConnectExternal}
                disabled={isConnecting || !externalUrl}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 rounded-lg bg-synor-600 hover:bg-synor-700 text-white font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isConnecting ? (
                  <RefreshCw size={18} className="animate-spin" />
                ) : (
                  <Power size={18} />
                )}
                Connect
              </button>
            </div>
          </div>

          {/* Embedded Node */}
          <div className="p-6 rounded-xl bg-gray-900 border border-gray-800">
            <div className="flex items-center gap-3 mb-4">
              <Server size={24} className="text-synor-400" />
              <h3 className="text-lg font-semibold text-white">Embedded Node</h3>
            </div>
            <p className="text-sm text-gray-400 mb-4">
              Run a full node inside the wallet. Requires more resources but provides maximum security.
            </p>
            <div className="space-y-3">
              <select
                value={embeddedNetwork}
                onChange={(e) => setEmbeddedNetwork(e.target.value)}
                className="w-full px-4 py-3 rounded-lg bg-gray-800 border border-gray-700 text-white focus:outline-none focus:border-synor-500"
              >
                <option value="mainnet">Mainnet</option>
                <option value="testnet">Testnet</option>
                <option value="devnet">Devnet</option>
              </select>
              <button
                onClick={handleStartEmbedded}
                disabled={isConnecting}
                className="w-full flex items-center justify-center gap-2 px-4 py-3 rounded-lg bg-gray-700 hover:bg-gray-600 text-white font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isConnecting ? (
                  <RefreshCw size={18} className="animate-spin" />
                ) : (
                  <Power size={18} />
                )}
                Start Node
              </button>
              <p className="text-xs text-gray-500 text-center">
                Requires embedded-node feature enabled
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Peers List (when connected) */}
      {status.isConnected && peers.length > 0 && (
        <div className="p-6 rounded-xl bg-gray-900 border border-gray-800">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-white flex items-center gap-2">
              <Users size={20} />
              Connected Peers
            </h3>
            <button
              onClick={refreshPeers}
              className="p-2 rounded-lg hover:bg-gray-800 text-gray-400 hover:text-white transition-colors"
            >
              <RefreshCw size={18} />
            </button>
          </div>
          <div className="space-y-2">
            {peers.slice(0, 10).map((peer) => (
              <div
                key={peer.peerId}
                className="flex items-center justify-between p-3 rounded-lg bg-gray-800"
              >
                <div className="flex items-center gap-3">
                  <div
                    className={`w-2 h-2 rounded-full ${
                      peer.status === 'connected' ? 'bg-green-400' : 'bg-gray-500'
                    }`}
                  />
                  <div>
                    <p className="text-sm text-white font-mono">
                      {peer.peerId.slice(0, 16)}...
                    </p>
                    <p className="text-xs text-gray-500">{peer.address}</p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-xs text-gray-400">{peer.direction}</p>
                  {peer.latencyMs !== undefined && (
                    <p className="text-xs text-gray-500">{peer.latencyMs}ms</p>
                  )}
                </div>
              </div>
            ))}
          </div>
          {peers.length > 10 && (
            <p className="text-xs text-gray-500 text-center mt-3">
              And {peers.length - 10} more peers...
            </p>
          )}
        </div>
      )}
    </div>
  );
}

// Stat card component
function StatCard({
  icon,
  label,
  value,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
}) {
  return (
    <div className="p-4 rounded-xl bg-gray-900 border border-gray-800">
      <div className="flex items-center gap-2 text-gray-400 mb-2">
        {icon}
        <span className="text-sm">{label}</span>
      </div>
      <p className="text-xl font-bold text-white">{value}</p>
    </div>
  );
}
