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

function generateSimpleFingerprint(): string {
  // 浏览器兼容的简单指纹生成
  const arr = new Uint8Array(32);
  crypto.getRandomValues(arr);
  return Array.from(arr, (b) => b.toString(16).padStart(2, '0')).join('');
}

export function DevicesPage() {
  const [devices, setDevices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [deviceName, setDeviceName] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

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

  useEffect(() => {
    loadDevices();
  }, []);

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSuccess('');

    if (!deviceName.trim()) {
      setError('设备名称不能为空');
      return;
    }

    const fingerprint = generateSimpleFingerprint();
    const res = await window.electronAPI.registerDevice({
      device_name: deviceName.trim(),
      device_fingerprint: fingerprint,
      public_key: '',
    });

    if (res.success) {
      setSuccess(`设备 "${deviceName}" 注册成功！`);
      setDeviceName('');
      loadDevices();
    } else {
      setError(res.message || '注册失败');
    }
  };

  const handleDelete = async (id: number) => {
    const res = await window.electronAPI.deleteDevice(id);
    if (res.success) {
      loadDevices();
    }
  };

  const handleToggleStatus = async (id: number, current: string) => {
    const newStatus = current === 'online' ? 'offline' : 'online';
    await window.electronAPI.updateDeviceStatus(id, newStatus);
    loadDevices();
  };

  return (
    <div className="page">
      <h1>设备管理</h1>

      <div className="card">
        <h3>注册新设备</h3>
        <form onSubmit={handleRegister} className="inline-form">
          <input
            type="text"
            value={deviceName}
            onChange={(e) => setDeviceName(e.target.value)}
            placeholder="设备名称，如：MacBook Pro"
            className="flex-input"
          />
          <button type="submit" className="btn-primary">注册设备</button>
        </form>
        {error && <div className="error-msg">{error}</div>}
        {success && <div className="success-msg">{success}</div>}
      </div>

      <div className="card">
        <h3>我的设备 ({devices.length})</h3>
        {loading ? (
          <p>加载中...</p>
        ) : devices.length === 0 ? (
          <p className="empty-text">暂无设备，请注册一个设备</p>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>名称</th>
                <th>指纹</th>
                <th>状态</th>
                <th>最后在线</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {devices.map((d) => (
                <tr key={d.id}>
                  <td>{d.id}</td>
                  <td>{d.device_name}</td>
                  <td className="mono">{d.device_fingerprint?.substring(0, 16)}...</td>
                  <td>
                    <span className={`status-badge ${d.status}`}>
                      {d.status === 'online' ? '🟢 在线' : '⚫ 离线'}
                    </span>
                  </td>
                  <td>{d.last_seen_at}</td>
                  <td>
                    <button
                      className="btn-sm"
                      onClick={() => handleToggleStatus(d.id, d.status)}
                    >
                      {d.status === 'online' ? '离线' : '上线'}
                    </button>
                    <button
                      className="btn-sm btn-danger"
                      onClick={() => handleDelete(d.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
