'use client';

/**
 * Network Status Indicator
 * 
 * Shows online/offline status prominently
 * With sync queue info and retry controls
 */

import { useState, useEffect } from 'react';
import { Wifi, WifiOff, Cloud, CloudOff, RefreshCw, X, AlertTriangle, CheckCircle } from 'lucide-react';

interface NetworkStatusProps {
  pendingCount?: number;
  failedCount?: number;
  isSyncing?: boolean;
  onRetryAll?: () => void;
  onDismiss?: () => void;
}

export function NetworkStatusIndicator({
  pendingCount = 0,
  failedCount = 0,
  isSyncing = false,
  onRetryAll,
  onDismiss,
}: NetworkStatusProps) {
  const [isOnline, setIsOnline] = useState(true);
  const [showBanner, setShowBanner] = useState(false);
  const [wasOffline, setWasOffline] = useState(false);

  useEffect(() => {
    const handleOnline = () => {
      setIsOnline(true);
      if (wasOffline) {
        // Show "back online" message briefly
        setShowBanner(true);
        setTimeout(() => setShowBanner(false), 3000);
      }
      setWasOffline(false);
    };

    const handleOffline = () => {
      setIsOnline(false);
      setWasOffline(true);
      setShowBanner(true);
    };

    setIsOnline(navigator.onLine);
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, [wasOffline]);

  // Show banner if offline or has pending/failed items
  const shouldShowBanner = showBanner || !isOnline || pendingCount > 0 || failedCount > 0;

  if (!shouldShowBanner) {
    return null;
  }

  return (
    <div
      className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${
        shouldShowBanner ? 'translate-y-0' : '-translate-y-full'
      }`}
    >
      <div
        className={`px-4 py-2 flex items-center justify-between text-sm ${
          !isOnline
            ? 'bg-red-500 text-white'
            : failedCount > 0
            ? 'bg-amber-500 text-white'
            : pendingCount > 0
            ? 'bg-blue-500 text-white'
            : 'bg-emerald-500 text-white'
        }`}
      >
        <div className="flex items-center gap-2">
          {!isOnline ? (
            <>
              <WifiOff className="h-4 w-4" />
              <span className="font-medium">You're offline</span>
              {pendingCount > 0 && (
                <span className="text-xs opacity-90">
                  • {pendingCount} delivery{pendingCount > 1 ? 'ies' : ''} queued
                </span>
              )}
            </>
          ) : failedCount > 0 ? (
            <>
              <AlertTriangle className="h-4 w-4" />
              <span className="font-medium">{failedCount} sync failed</span>
            </>
          ) : pendingCount > 0 ? (
            <>
              {isSyncing ? (
                <RefreshCw className="h-4 w-4 animate-spin" />
              ) : (
                <Cloud className="h-4 w-4" />
              )}
              <span className="font-medium">
                {isSyncing ? 'Syncing...' : `${pendingCount} pending sync`}
              </span>
            </>
          ) : (
            <>
              <CheckCircle className="h-4 w-4" />
              <span className="font-medium">Back online</span>
            </>
          )}
        </div>

        <div className="flex items-center gap-2">
          {(failedCount > 0 || (pendingCount > 0 && !isSyncing)) && isOnline && onRetryAll && (
            <button
              onClick={onRetryAll}
              className="flex items-center gap-1 rounded-full bg-white/20 px-2 py-1 text-xs font-medium hover:bg-white/30 transition-colors"
            >
              <RefreshCw className="h-3 w-3" />
              Retry
            </button>
          )}
          {onDismiss && isOnline && pendingCount === 0 && failedCount === 0 && (
            <button
              onClick={() => {
                setShowBanner(false);
                onDismiss();
              }}
              className="p-1 hover:bg-white/20 rounded-full transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// Compact status badge for navbar/header
export function NetworkStatusBadge() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    setIsOnline(navigator.onLine);
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return (
    <div
      className={`flex items-center gap-1.5 rounded-full px-2 py-1 text-xs font-medium transition-colors ${
        isOnline
          ? 'bg-emerald-100 text-emerald-700'
          : 'bg-red-100 text-red-700 animate-pulse'
      }`}
    >
      {isOnline ? (
        <>
          <div className="h-2 w-2 rounded-full bg-emerald-500" />
          <span>Online</span>
        </>
      ) : (
        <>
          <WifiOff className="h-3 w-3" />
          <span>Offline</span>
        </>
      )}
    </div>
  );
}

// Hook for network status
export function useNetworkStatus() {
  const [isOnline, setIsOnline] = useState(true);
  const [connectionType, setConnectionType] = useState<string>('unknown');

  useEffect(() => {
    const updateStatus = () => {
      setIsOnline(navigator.onLine);
      
      // @ts-ignore - Network Information API
      const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
      if (connection) {
        setConnectionType(connection.effectiveType || 'unknown');
      }
    };

    updateStatus();
    window.addEventListener('online', updateStatus);
    window.addEventListener('offline', updateStatus);

    // @ts-ignore
    const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    if (connection) {
      connection.addEventListener('change', updateStatus);
    }

    return () => {
      window.removeEventListener('online', updateStatus);
      window.removeEventListener('offline', updateStatus);
      if (connection) {
        connection.removeEventListener('change', updateStatus);
      }
    };
  }, []);

  return { isOnline, connectionType };
}
