import { useState, useEffect } from 'react'
import { RefreshCw, AlertCircle, CheckCircle } from 'lucide-react'
import { api } from '../services/api'

interface SyncStatusData {
  pendingItems: number
  recentSync: any[]
  pendingConflicts: number
  isSyncing: boolean
}

export default function SyncStatus() {
  const [status, setStatus] = useState<SyncStatusData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    fetchStatus()
    
    // Refresh every 30 seconds
    const interval = setInterval(fetchStatus, 30000)
    return () => clearInterval(interval)
  }, [])

  const fetchStatus = async () => {
    try {
      const response = await api.get('/sync/status')
      setStatus(response.data.data)
      setError('')
    } catch (err) {
      console.error('Failed to fetch sync status:', err)
      setError('Fehler beim Abrufen des Sync-Status')
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow p-4">
        <div className="animate-pulse">
          <div className="h-4 bg-gray-200 rounded w-1/3 mb-2"></div>
          <div className="h-8 bg-gray-200 rounded w-1/2"></div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-white rounded-lg shadow p-4">
        <div className="flex items-center text-red-600">
          <AlertCircle className="w-5 h-5 mr-2" />
          <span className="text-sm">{error}</span>
        </div>
      </div>
    )
  }

  if (!status) return null

  return (
    <div className="bg-white rounded-lg shadow p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">Sync-Status</h3>
        <button
          onClick={fetchStatus}
          className="text-gray-500 hover:text-gray-700"
        >
          <RefreshCw className={`w-5 h-5 ${status.isSyncing ? 'animate-spin' : ''}`} />
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4 text-sm">
        <div>
          <div className="text-gray-500">Ausstehend</div>
          <div className="text-2xl font-bold text-gray-900">{status.pendingItems}</div>
        </div>
        
        <div>
          <div className="text-gray-500">Konflikte</div>
          <div className="text-2xl font-bold text-orange-600">{status.pendingConflicts}</div>
        </div>
        
        <div>
          <div className="text-gray-500">Status</div>
          <div className="mt-1">
            {status.isSyncing ? (
              <span className="flex items-center text-blue-600">
                <RefreshCw className="w-4 h-4 mr-1 animate-spin" />
                Läuft...
              </span>
            ) : (
              <span className="flex items-center text-green-600">
                <CheckCircle className="w-4 h-4 mr-1" />
                Bereit
              </span>
            )}
          </div>
        </div>
      </div>

      {status.recentSync && status.recentSync.length > 0 && (
        <div className="mt-4 pt-4 border-t border-gray-200">
          <h4 className="text-sm font-medium text-gray-700 mb-2">Letzte Sync-Vorgänge</h4>
          <div className="space-y-1">
            {status.recentSync.slice(0, 3).map((sync, index) => (
              <div key={index} className="flex items-center justify-between text-xs">
                <span className="text-gray-600">
                  {sync.sync_type} - {sync.sync_action}
                </span>
                <span className={`px-2 py-1 rounded-full ${
                  sync.status === 'completed' ? 'bg-green-100 text-green-800' :
                  sync.status === 'failed' ? 'bg-red-100 text-red-800' :
                  sync.status === 'conflict' ? 'bg-orange-100 text-orange-800' :
                  'bg-gray-100 text-gray-800'
                }`}>
                  {sync.status === 'completed' ? 'Erfolgreich' :
                   sync.status === 'failed' ? 'Fehlgeschlagen' :
                   sync.status === 'conflict' ? 'Konflikt' :
                   'Ausstehend'}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}