'use client';

import { Button } from '@/components/ui/button';
import { useSync } from '@/hooks/use-sync';
import { cn } from '@/lib/utils';
import { CheckCircle2, RefreshCw, WifiOff } from 'lucide-react';

export function GlobalSyncStatus({ compact = false }: { compact?: boolean }) {
  const { isOnline, isSyncing, lastError, pendingCount, syncNow } = useSync();

  const hasWarning = !isOnline || pendingCount > 0 || Boolean(lastError);
  const label = !isOnline
    ? 'Sin conexión'
    : pendingCount > 0
      ? `${pendingCount} pendiente${pendingCount === 1 ? '' : 's'}`
      : lastError
        ? 'Error al sincronizar'
        : isSyncing
          ? 'Sincronizando'
          : 'Sincronizado';

  return (
    <div
      className={cn(
        'flex items-center gap-2 rounded-2xl border bg-surface shadow-sm',
        compact ? 'px-3 py-2' : 'px-3 py-2.5',
        hasWarning ? 'border-amber-200 text-amber-700' : 'border-emerald-100 text-emerald-700',
      )}
    >
      {!isOnline ? (
        <WifiOff className="h-4 w-4 shrink-0" />
      ) : isSyncing ? (
        <RefreshCw className="h-4 w-4 shrink-0 animate-spin" />
      ) : (
        <CheckCircle2 className="h-4 w-4 shrink-0" />
      )}
      <div className="min-w-0">
        <p className="truncate text-xs font-bold">{label}</p>
        {!compact ? <p className="text-[11px] text-muted-foreground">{hasWarning ? 'Los cambios se reintentan solos' : 'Datos al día'}</p> : null}
      </div>
      {isOnline && (pendingCount > 0 || lastError) ? (
        <Button size="sm" variant="ghost" className="h-8 rounded-xl px-2 text-xs" onClick={() => void syncNow()} disabled={isSyncing}>
          Reintentar
        </Button>
      ) : null}
    </div>
  );
}
