import { useState, useEffect } from 'react'
import { Plus, Trash2, Edit2, Save, X, RefreshCw, Monitor, Globe } from 'lucide-react'
import { networkApi, NetworkNode, SyncSettings as SyncSettingsType } from '../services/networkApi'

export default function SyncSettings() {
  const [nodes, setNodes] = useState<NetworkNode[]>([])
  const [editingNode, setEditingNode] = useState<string | null>(null)
  const [newNode, setNewNode] = useState<Partial<NetworkNode>>({
    name: '',
    location: '',
    ipAddress: '',
    port: 3005,
    apiKey: '',
    type: 'local'
  })
  const [showNewNodeForm, setShowNewNodeForm] = useState(false)
  const [syncStatus, setSyncStatus] = useState<'idle' | 'syncing' | 'success' | 'error'>('idle')
  const [syncSettings, setSyncSettings] = useState<SyncSettingsType>({
    autoSyncInterval: 'disabled',
    conflictResolution: 'admin',
    syncEmployees: true,
    syncSkills: true,
    syncUsers: true,
    syncSettings: false,
    bandwidthLimit: null
  })

  useEffect(() => {
    // Load nodes and settings from backend
    fetchNodes()
    fetchSyncSettings()
  }, [])

  const fetchNodes = async () => {
    try {
      const data = await networkApi.getNodes()
      setNodes(data)
    } catch (error) {
      console.error('Failed to fetch nodes:', error)
    }
  }

  const fetchSyncSettings = async () => {
    try {
      const data = await networkApi.getSyncSettings()
      setSyncSettings(data)
    } catch (error) {
      console.error('Failed to fetch sync settings:', error)
    }
  }

  const handleAddNode = async () => {
    try {
      const result = await networkApi.createNode({
        name: newNode.name || '',
        location: newNode.location || '',
        ipAddress: newNode.ipAddress || '',
        port: newNode.port || 3005,
        type: newNode.type as 'admin' | 'local'
      })
      
      // Refresh nodes list
      await fetchNodes()
      
      setNewNode({
        name: '',
        location: '',
        ipAddress: '',
        port: 3005,
        apiKey: '',
        type: 'local'
      })
      setShowNewNodeForm(false)
      
      // Show API key to user
      alert(`Node created successfully!\n\nAPI Key: ${result.apiKey}\n\nPlease save this key securely. It won't be shown again.`)
    } catch (error) {
      console.error('Failed to add node:', error)
      alert('Failed to add node')
    }
  }

  const handleUpdateNode = async (nodeId: string, updates: Partial<NetworkNode>) => {
    try {
      await networkApi.updateNode(nodeId, updates)
      setNodes(nodes.map(node => 
        node.id === nodeId ? { ...node, ...updates } : node
      ))
      setEditingNode(null)
    } catch (error) {
      console.error('Failed to update node:', error)
      alert('Failed to update node')
    }
  }

  const handleDeleteNode = async (nodeId: string) => {
    if (!confirm('Sind Sie sicher, dass Sie diesen Knoten löschen möchten?')) {
      return
    }

    try {
      await networkApi.deleteNode(nodeId)
      setNodes(nodes.filter(node => node.id !== nodeId))
    } catch (error) {
      console.error('Failed to delete node:', error)
      alert('Failed to delete node')
    }
  }

  const handleSyncAll = async () => {
    setSyncStatus('syncing')
    try {
      await networkApi.triggerSync()
      setSyncStatus('success')
      setTimeout(() => setSyncStatus('idle'), 3000)
      // Refresh nodes to update sync status
      fetchNodes()
    } catch (error) {
      setSyncStatus('error')
      setTimeout(() => setSyncStatus('idle'), 3000)
    }
  }

  const handleSaveSyncSettings = async () => {
    try {
      await networkApi.updateSyncSettings(syncSettings)
      alert('Sync settings saved successfully')
    } catch (error) {
      console.error('Failed to save sync settings:', error)
      alert('Failed to save sync settings')
    }
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-gray-900">
          Netzwerk & Synchronisation
        </h1>
        <div className="flex space-x-4">
          <button
            onClick={handleSyncAll}
            disabled={syncStatus === 'syncing'}
            className={`flex items-center space-x-2 px-4 py-2 rounded-lg transition-colors ${
              syncStatus === 'syncing' 
                ? 'bg-gray-300 cursor-not-allowed' 
                : 'bg-green-600 hover:bg-green-700 text-white'
            }`}
          >
            <RefreshCw className={`w-5 h-5 ${syncStatus === 'syncing' ? 'animate-spin' : ''}`} />
            <span>
              {syncStatus === 'syncing' ? 'Synchronisiere...' : 
               syncStatus === 'success' ? 'Erfolgreich!' :
               syncStatus === 'error' ? 'Fehler!' : 'Alle synchronisieren'}
            </span>
          </button>
          <button
            onClick={() => setShowNewNodeForm(true)}
            className="flex items-center space-x-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors"
          >
            <Plus className="w-5 h-5" />
            <span>Knoten hinzufügen</span>
          </button>
        </div>
      </div>

      {/* Network Overview */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center justify-between mb-4">
            <Globe className="w-8 h-8 text-blue-600" />
            <span className="text-2xl font-bold text-gray-900">{nodes.length}</span>
          </div>
          <h3 className="text-lg font-semibold text-gray-700">Gesamte Knoten</h3>
          <p className="text-sm text-gray-500">Im Netzwerk</p>
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center justify-between mb-4">
            <Monitor className="w-8 h-8 text-green-600" />
            <span className="text-2xl font-bold text-gray-900">
              {nodes.filter(n => n.isOnline).length}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-700">Online</h3>
          <p className="text-sm text-gray-500">Aktive Verbindungen</p>
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center justify-between mb-4">
            <RefreshCw className="w-8 h-8 text-blue-600" />
            <span className="text-sm font-medium text-gray-900">
              {nodes[0]?.lastSync ? new Date(nodes[0].lastSync).toLocaleString('de-DE') : 'Nie'}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-700">Letzte Sync</h3>
          <p className="text-sm text-gray-500">Admin-Knoten</p>
        </div>
      </div>

      {/* New Node Form */}
      {showNewNodeForm && (
        <div className="bg-white rounded-lg shadow mb-6 p-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">
            Neuen Knoten hinzufügen
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Name
              </label>
              <input
                type="text"
                value={newNode.name || ''}
                onChange={(e) => setNewNode({ ...newNode, name: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="z.B. Außenstelle Frankfurt"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Standort
              </label>
              <input
                type="text"
                value={newNode.location || ''}
                onChange={(e) => setNewNode({ ...newNode, location: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="z.B. Frankfurt, Deutschland"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                IP-Adresse
              </label>
              <input
                type="text"
                value={newNode.ipAddress || ''}
                onChange={(e) => setNewNode({ ...newNode, ipAddress: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="z.B. 192.168.1.100"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Port
              </label>
              <input
                type="number"
                value={newNode.port || 3005}
                onChange={(e) => setNewNode({ ...newNode, port: parseInt(e.target.value) })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Typ
              </label>
              <select
                value={newNode.type || 'local'}
                onChange={(e) => setNewNode({ ...newNode, type: e.target.value as 'admin' | 'local' })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="local">Lokaler Knoten</option>
                <option value="admin">Admin Knoten</option>
              </select>
            </div>
          </div>

          <div className="flex justify-end space-x-3 mt-6">
            <button
              onClick={() => setShowNewNodeForm(false)}
              className="px-4 py-2 text-gray-700 bg-gray-200 hover:bg-gray-300 rounded-lg transition-colors"
            >
              Abbrechen
            </button>
            <button
              onClick={handleAddNode}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
            >
              Hinzufügen
            </button>
          </div>
        </div>
      )}

      {/* Nodes List */}
      <div className="bg-white rounded-lg shadow">
        <div className="px-6 py-4 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            Netzwerkknoten
          </h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Standort
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  IP-Adresse
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Typ
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Letzte Sync
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Aktionen
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {nodes.map((node) => (
                <tr key={node.id}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className={`w-3 h-3 rounded-full ${
                      node.isOnline ? 'bg-green-500' : 'bg-red-500'
                    }`} />
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {editingNode === node.id ? (
                      <input
                        type="text"
                        value={node.name}
                        onChange={(e) => handleUpdateNode(node.id, { name: e.target.value })}
                        className="px-2 py-1 border border-gray-300 rounded"
                      />
                    ) : (
                      <span className="text-sm font-medium text-gray-900">{node.name}</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {node.location}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {node.ipAddress}:{node.port}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                      node.type === 'admin' 
                        ? 'bg-purple-100 text-purple-800' 
                        : 'bg-blue-100 text-blue-800'
                    }`}>
                      {node.type === 'admin' ? 'Admin' : 'Lokal'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {node.lastSync ? new Date(node.lastSync).toLocaleString('de-DE') : 'Nie'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex space-x-2">
                      {editingNode === node.id ? (
                        <>
                          <button
                            onClick={() => setEditingNode(null)}
                            className="text-green-600 hover:text-green-900"
                          >
                            <Save className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => setEditingNode(null)}
                            className="text-gray-600 hover:text-gray-900"
                          >
                            <X className="w-4 h-4" />
                          </button>
                        </>
                      ) : (
                        <>
                          <button
                            onClick={() => setEditingNode(node.id)}
                            className="text-blue-600 hover:text-primary-900"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleDeleteNode(node.id)}
                            className="text-red-600 hover:text-red-900"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Sync Configuration */}
      <div className="mt-8 bg-white rounded-lg shadow p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">
          Synchronisationseinstellungen
        </h2>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Automatische Synchronisation
            </label>
            <select 
              value={syncSettings.autoSyncInterval}
              onChange={(e) => setSyncSettings({ ...syncSettings, autoSyncInterval: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="disabled">Deaktiviert</option>
              <option value="5min">Alle 5 Minuten</option>
              <option value="15min">Alle 15 Minuten</option>
              <option value="30min">Alle 30 Minuten</option>
              <option value="1hour">Jede Stunde</option>
              <option value="daily">Täglich</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Konfliktauflösung
            </label>
            <select 
              value={syncSettings.conflictResolution}
              onChange={(e) => setSyncSettings({ ...syncSettings, conflictResolution: e.target.value as 'admin' | 'newest' | 'manual' })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="admin">Admin hat Vorrang</option>
              <option value="newest">Neueste Änderung gewinnt</option>
              <option value="manual">Manuell auflösen</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Daten-Synchronisation
            </label>
            <div className="space-y-2">
              <label className="flex items-center">
                <input 
                  type="checkbox" 
                  className="mr-2" 
                  checked={syncSettings.syncEmployees}
                  onChange={(e) => setSyncSettings({ ...syncSettings, syncEmployees: e.target.checked })}
                />
                <span className="text-sm">Daten der Mitarbeitenden</span>
              </label>
              <label className="flex items-center">
                <input 
                  type="checkbox" 
                  className="mr-2" 
                  checked={syncSettings.syncSkills}
                  onChange={(e) => setSyncSettings({ ...syncSettings, syncSkills: e.target.checked })}
                />
                <span className="text-sm">Skills und Qualifikationen</span>
              </label>
              <label className="flex items-center">
                <input 
                  type="checkbox" 
                  className="mr-2" 
                  checked={syncSettings.syncUsers}
                  onChange={(e) => setSyncSettings({ ...syncSettings, syncUsers: e.target.checked })}
                />
                <span className="text-sm">Benutzerkonten</span>
              </label>
              <label className="flex items-center">
                <input 
                  type="checkbox" 
                  className="mr-2" 
                  checked={syncSettings.syncSettings}
                  onChange={(e) => setSyncSettings({ ...syncSettings, syncSettings: e.target.checked })}
                />
                <span className="text-sm">Systemeinstellungen</span>
              </label>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Bandbreitenbegrenzung
            </label>
            <div className="flex items-center space-x-3">
              <input
                type="number"
                placeholder="Unbegrenzt"
                value={syncSettings.bandwidthLimit || ''}
                onChange={(e) => setSyncSettings({ ...syncSettings, bandwidthLimit: e.target.value ? parseInt(e.target.value) : null })}
                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              <span className="text-sm text-gray-500">KB/s</span>
            </div>
          </div>
        </div>

        <div className="mt-6 flex justify-end">
          <button 
            onClick={handleSaveSyncSettings}
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            Einstellungen speichern
          </button>
        </div>
      </div>
    </div>
  )
}
