/**
 * Offline Indicator Component
 * 
 * This component displays the current network status and offline queue information.
 * It shows:
 * - Network status (online/offline)
 * - Number of pending operations in the offline queue
 * - Sync progress when syncing
 * - Manual sync button
 * 
 * Requirements: REQ-5.5.1
 */

'use client';

import React from 'react';
import { useOfflineSync } from '@/lib/hooks/useOfflineSync';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { 
  WifiOff, 
  Wifi, 
  RefreshCw, 
  CheckCircle2, 
  AlertCircle,
  Loader2 
} from 'lucide-react';
import { cn } from '@/utils';

interface OfflineIndicatorProps {
  /** Additional CSS classes */
  className?: string;
  
  /** Whether to show when online (default: false) */
  showWhenOnline?: boolean;
  
  /** Position of the indicator (default: 'top-right') */
  position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
  
  /** Whether to show the manual sync button (default: true) */
  showSyncButton?: boolean;
}

/**
 * Offline Indicator Component
 * 
 * Displays network status and offline queue information.
 * Automatically syncs when network is restored.
 * 
 * @example
 * ```tsx
 * // Basic usage
 * <OfflineIndicator />
 * 
 * // Custom position
 * <OfflineIndicator position="bottom-right" />
 * 
 * // Show when online
 * <OfflineIndicator showWhenOnline />
 * ```
 */
export function OfflineIndicator({
  className,
  showWhenOnline = false,
  position = 'top-right',
  showSyncButton = true
}: OfflineIndicatorProps) {
  const {
    isOnline,
    isSyncing,
    syncStatus,
    queueSize,
    syncProgress,
    syncTotal,
    syncError,
    manualSync,
    clearError
  } = useOfflineSync();

  // Don't show if online and showWhenOnline is false
  if (isOnline && !showWhenOnline && queueSize === 0) {
    return null;
  }

  // Position classes
  const positionClasses = {
    'top-left': 'top-4 left-4',
    'top-right': 'top-4 right-4',
    'bottom-left': 'bottom-4 left-4',
    'bottom-right': 'bottom-4 right-4'
  };

  return (
    <div
      className={cn(
        'fixed z-50 flex items-center gap-2 rounded-lg border bg-background/95 backdrop-blur-sm p-3 shadow-lg transition-all',
        positionClasses[position],
        className
      )}
    >
      {/* Network Status Icon */}
      <div className="flex items-center gap-2">
        {isOnline ? (
          <Wifi className="h-4 w-4 text-green-500" />
        ) : (
          <WifiOff className="h-4 w-4 text-orange-500" />
        )}
        
        {/* Status Text */}
        <span className="text-sm font-medium">
          {isOnline ? 'Online' : 'Offline'}
        </span>
      </div>

      {/* Queue Size Badge */}
      {queueSize > 0 && (
        <Badge variant="secondary" className="ml-1">
          {queueSize} pending
        </Badge>
      )}

      {/* Sync Status */}
      {isSyncing && (
        <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
          <Loader2 className="h-3.5 w-3.5 animate-spin" />
          <span>
            Syncing {syncProgress}/{syncTotal}...
          </span>
        </div>
      )}

      {syncStatus === 'completed' && !isSyncing && (
        <div className="flex items-center gap-1.5 text-sm text-green-600">
          <CheckCircle2 className="h-3.5 w-3.5" />
          <span>Synced</span>
        </div>
      )}

      {syncError && (
        <div className="flex items-center gap-1.5 text-sm text-destructive">
          <AlertCircle className="h-3.5 w-3.5" />
          <span className="max-w-[200px] truncate" title={syncError}>
            {syncError}
          </span>
          <Button
            variant="ghost"
            size="sm"
            className="h-6 px-2"
            onClick={clearError}
          >
            Dismiss
          </Button>
        </div>
      )}

      {/* Manual Sync Button */}
      {showSyncButton && queueSize > 0 && !isSyncing && (
        <Button
          variant="outline"
          size="sm"
          className="h-7 px-2"
          onClick={manualSync}
          disabled={!isOnline}
        >
          <RefreshCw className="h-3.5 w-3.5 mr-1" />
          Sync Now
        </Button>
      )}
    </div>
  );
}

/**
 * Compact Offline Indicator
 * 
 * A minimal version that only shows an icon with a badge.
 * Useful for toolbars or headers where space is limited.
 * 
 * @example
 * ```tsx
 * <CompactOfflineIndicator />
 * ```
 */
export function CompactOfflineIndicator({ className }: { className?: string }) {
  const { isOnline, queueSize, isSyncing } = useOfflineSync();

  if (isOnline && queueSize === 0) {
    return null;
  }

  return (
    <div className={cn('relative inline-flex items-center', className)}>
      {isOnline ? (
        <Wifi className="h-4 w-4 text-green-500" />
      ) : (
        <WifiOff className="h-4 w-4 text-orange-500" />
      )}
      
      {queueSize > 0 && (
        <Badge 
          variant="destructive" 
          className="absolute -top-1 -right-1 h-4 min-w-4 px-1 text-[10px] flex items-center justify-center"
        >
          {queueSize}
        </Badge>
      )}
      
      {isSyncing && (
        <Loader2 className="absolute -bottom-1 -right-1 h-3 w-3 animate-spin text-primary" />
      )}
    </div>
  );
}

/**
 * Offline Banner
 * 
 * A full-width banner that appears at the top of the page when offline.
 * More prominent than the indicator for critical offline notifications.
 * 
 * @example
 * ```tsx
 * <OfflineBanner />
 * ```
 */
export function OfflineBanner({ className }: { className?: string }) {
  const { isOnline, queueSize, isSyncing, syncProgress, syncTotal, manualSync } = useOfflineSync();

  if (isOnline && queueSize === 0) {
    return null;
  }

  return (
    <div
      className={cn(
        'w-full border-b bg-orange-50 dark:bg-orange-950/20 px-4 py-2',
        className
      )}
    >
      <div className="container mx-auto flex items-center justify-between">
        <div className="flex items-center gap-3">
          <WifiOff className="h-5 w-5 text-orange-600 dark:text-orange-400" />
          <div>
            <p className="text-sm font-medium text-orange-900 dark:text-orange-100">
              {isOnline ? 'Connection Restored' : 'You are offline'}
            </p>
            {queueSize > 0 && (
              <p className="text-xs text-orange-700 dark:text-orange-300">
                {queueSize} operation{queueSize !== 1 ? 's' : ''} pending sync
              </p>
            )}
          </div>
        </div>

        {isOnline && queueSize > 0 && (
          <Button
            variant="outline"
            size="sm"
            onClick={manualSync}
            disabled={isSyncing}
            className="border-orange-300 dark:border-orange-700"
          >
            {isSyncing ? (
              <>
                <Loader2 className="h-3.5 w-3.5 mr-2 animate-spin" />
                Syncing {syncProgress}/{syncTotal}...
              </>
            ) : (
              <>
                <RefreshCw className="h-3.5 w-3.5 mr-2" />
                Sync Now
              </>
            )}
          </Button>
        )}
      </div>
    </div>
  );
}
