import React, { useState, useEffect, useRef } from 'react';

export function ConnectionsPage() {
  const [devices, setDevices] = useState<any[]>([]);
  const [nodes, setNodes] = useState<any[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<number | null>(null);
  const [selectedNode, setSelectedNode] = useState<number | null>(null);
  const [connected, setConnected] = useState(false);
  const [relayStatus, setRelayStatus] = useState('disconnected');
  const [messages, setMessages] = useState<{ text: string; incoming: boolean; time: string }[]>([]);
  const [draftMessage, setDraftMessage] = useState('');
  const [targetDeviceId, setTargetDeviceId] = useState('');
  const [error, setError] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    loadDevices();
    loadNodes();

    window.electronAPI.onRelayMessage((msg) => {
      if (msg.type === 'data') {
        setMessages((prev) => [
          ...prev,
          {
            text: msg.payload,
            incoming: true,
            time: new Date(msg.timestamp).toLocaleTimeString(),
          },
        ]);
      } else if (msg.type === 'error') {
        setMessages((prev) => [
          ...prev,
          {
            text: `[错误] ${msg.payload}`,
            incoming: true,
            time: new Date(msg.timestamp).toLocaleTimeString(),
          },
        ]);
      }
    });

    window.electronAPI.onRelayStatus((status) => {
      setRelayStatus(status);
      if (status === 'authenticated') {
        setConnected(true);
        setError('');
        setMessages((prev) => [
          ...prev,
          { text: '✅ 已连接到转发节点', incoming: true, time: new Date().toLocaleTimeString() },
        ]);
      } else if (status === 'disconnected') {
        setConnected(false);
      } else if (status === 'error') {
        setError('连接失败');
      }
    });

    return () => {
      window.electronAPI.removeRelayListeners();
    };
  }, []);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const loadDevices = async () => {
    const res = await window.electronAPI.listDevices();
    if (res.success) setDevices(res.data);
  };

  const loadNodes = async () => {
    const res = await window.electronAPI.getAvailableNodes();
    if (res.success) setNodes(res.data);
  };

  const handleConnect = async () => {
    if (!selectedDevice || !selectedNode) {
      setError('请选择设备和节点');
      return;
    }

    setError('');
    setMessages([]);

    const res = await window.electronAPI.requestConnection({
      device_id: selectedDevice,
      node_id: selectedNode,
    });

    if (!res.success) {
      setError(res.message || '请求连接失败');
      return;
    }

    const { token, node } = res.data;
    const relayRes = await window.electronAPI.connectToRelay(
      node.host,
      node.port,
      token,
      selectedDevice
    );

    if (!relayRes.success) {
      setError(relayRes.message || '连接节点失败');
      await window.electronAPI.updateDeviceStatus(selectedDevice, 'offline');
    }
  };

  const handleDisconnect = async () => {
    await window.electronAPI.disconnectFromRelay();
    if (selectedDevice) {
      await window.electronAPI.updateDeviceStatus(selectedDevice, 'offline');
      await window.electronAPI.disconnect(selectedDevice);
    }
    setConnected(false);
    setMessages((prev) => [
      ...prev,
      { text: '🔌 已断开连接', incoming: true, time: new Date().toLocaleTimeString() },
    ]);
  };

  const handleSendMessage = async () => {
    if (!draftMessage.trim() || !targetDeviceId) return;

    await window.electronAPI.sendRelayMessage(parseInt(targetDeviceId), draftMessage.trim());
    setMessages((prev) => [
      ...prev,
      { text: draftMessage.trim(), incoming: false, time: new Date().toLocaleTimeString() },
    ]);
    setDraftMessage('');
  };

  return (
    <div className="page">
      <h1>网络连接</h1>

      {!connected ? (
        <div className="card">
          <h3>建立连接</h3>
          <div className="form-group">
            <label>选择设备</label>
            <select
              value={selectedDevice || ''}
              onChange={(e) => setSelectedDevice(parseInt(e.target.value))}
            >
              <option value="">-- 选择设备 --</option>
              {devices.map((d) => (
                <option key={d.id} value={d.id}>
                  {d.device_name} (ID: {d.id}, {d.status})
                </option>
              ))}
            </select>
          </div>
          <div className="form-group">
            <label>选择节点</label>
            <select
              value={selectedNode || ''}
              onChange={(e) => setSelectedNode(parseInt(e.target.value))}
            >
              <option value="">-- 选择节点 --</option>
              {nodes.map((n) => (
                <option key={n.id} value={n.id}>
                  {n.name} ({n.host}:{n.port}, 负载: {n.load})
                </option>
              ))}
            </select>
          </div>
          {error && <div className="error-msg">{error}</div>}
          <button className="btn-primary" onClick={handleConnect}>
            连接
          </button>
        </div>
      ) : (
        <div className="connection-active">
          <div className="card connection-header">
            <span>状态: {relayStatus === 'authenticated' ? '🟢 已连接' : '🟡 连接中...'}</span>
            <button className="btn-danger" onClick={handleDisconnect}>
              断开连接
            </button>
          </div>

          <div className="card">
            <h3>消息发送</h3>
            <div className="inline-form">
              <input
                type="number"
                value={targetDeviceId}
                onChange={(e) => setTargetDeviceId(e.target.value)}
                placeholder="目标设备 ID"
                className="small-input"
              />
              <input
                type="text"
                value={draftMessage}
                onChange={(e) => setDraftMessage(e.target.value)}
                placeholder="输入消息..."
                className="flex-input"
                onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
              />
              <button className="btn-primary" onClick={handleSendMessage}>
                发送
              </button>
            </div>
          </div>

          <div className="card">
            <h3>消息记录</h3>
            <div className="message-log">
              {messages.length === 0 ? (
                <p className="empty-text">暂无消息</p>
              ) : (
                messages.map((msg, i) => (
                  <div key={i} className={`message ${msg.incoming ? 'incoming' : 'outgoing'}`}>
                    <span className="msg-time">{msg.time}</span>
                    <span className="msg-arrow">{msg.incoming ? '←' : '→'}</span>
                    <span className="msg-text">{msg.text}</span>
                  </div>
                ))
              )}
              <div ref={messagesEndRef} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
