import { useState, useEffect } from 'react'
import { syncProgressManager } from '@/lib/syncProgressManager'
import type { SyncProgress } from '@/lib/userContentSync'
import { t } from '@/lib/i18n'

// Extract relay name from URL (remove wss:// and truncate if too long)
function getRelayDisplayName(relayUrl?: string): string {
  if (!relayUrl) {
    return ''
  }
  const cleaned = relayUrl.replace(/^wss?:\/\//, '').replace(/\/$/, '')
  if (cleaned.length > 50) {
    return `${cleaned.substring(0, 47)}...`
  }
  return cleaned
}

// Spinning sync icon
function SyncIcon(): React.ReactElement {
  return (
    <svg
      className="animate-spin h-4 w-4 text-neon-cyan"
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      viewBox="0 0 24 24"
    >
      <circle
        className="opacity-25"
        cx="12"
        cy="12"
        r="10"
        stroke="currentColor"
        strokeWidth="4"
      />
      <path
        className="opacity-75"
        fill="currentColor"
        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
      />
    </svg>
  )
}

/**
 * Sync status indicator component for display in header next to key icon
 * Shows sync icon + relay name when syncing
 */
export function SyncStatus(): React.ReactElement | null {
  const [progress, setProgress] = useState<SyncProgress | null>(() => syncProgressManager.getProgress())

  useEffect(() => {
    const unsubscribe = syncProgressManager.subscribe((newProgress) => {
      setProgress(newProgress)
    })

    return () => {
      unsubscribe()
    }
  }, [])

  // Show indicator if we have progress and it's not completed
  if (!progress) {
    return null
  }

  // Always show indicator during sync, even if completed is false (means sync is in progress)
  if (progress.completed) {
    return null
  }

  const relayName = progress.currentRelay ? getRelayDisplayName(progress.currentRelay) : null

  return (
    <div className="flex items-center gap-2 ml-2" title={relayName ?? t('settings.sync.connecting')}>
      <SyncIcon />
      {relayName ? (
        <span className="text-neon-cyan text-xs font-mono max-w-[200px] truncate">
          {relayName}
        </span>
      ) : (
        <span className="text-cyber-accent/70 text-xs italic">
          {t('settings.sync.connecting')}
        </span>
      )}
    </div>
  )
}

/**
 * Global sync progress bar (deprecated - kept for backward compatibility)
 * @deprecated Use SyncStatus component in KeyManagementManager instead
 */
export function GlobalSyncProgressBar(): React.ReactElement | null {
  return null
}
