"use client";

import { RefreshCw, CloudOff } from "lucide-react";
import { useOfflineSync } from "@/hooks/useOfflineSync";

interface SyncStatusProps {
  compact?: boolean;
  showLabel?: boolean;
}

export default function SyncStatus({ compact = false, showLabel = false }: SyncStatusProps) {
  const { pendingCount, syncing, online, sync } = useOfflineSync();

  const handleSync = async () => {
    await sync();
  };

  // Versión compacta para el header
  if (compact) {
    return (
      <button
        onClick={handleSync}
        disabled={syncing || (!online && pendingCount === 0)}
        className="relative p-2 rounded-full hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        title={
          !online
            ? "Sin conexión"
            : pendingCount > 0
            ? `${pendingCount} operación${pendingCount > 1 ? "es" : ""} pendiente${pendingCount > 1 ? "s" : ""}`
            : "Todo sincronizado"
        }
      >
        {!online ? (
          <CloudOff className="w-5 h-5 text-orange-600" />
        ) : (
          <RefreshCw
            className={`w-5 h-5 ${
              syncing
                ? "animate-spin text-blue-600"
                : pendingCount > 0
                ? "text-orange-600"
                : "text-green-600"
            }`}
          />
        )}
        {pendingCount > 0 && (
          <span className="absolute -top-1 -right-1 bg-orange-600 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center font-bold">
            {pendingCount > 9 ? "9+" : pendingCount}
          </span>
        )}
      </button>
    );
  }

  // Versión completa
  return (
    <div className="flex items-center gap-2 text-sm">
      {online ? (
        <>
          {pendingCount > 0 && (
            <>
              <span className="text-gray-600">
                {pendingCount} pendiente{pendingCount > 1 ? "s" : ""}
              </span>
              <button
                onClick={handleSync}
                disabled={syncing}
                className="flex items-center gap-1 text-blue-600 hover:text-blue-700 disabled:opacity-50"
              >
                <RefreshCw
                  className={`w-4 h-4 ${syncing ? "animate-spin" : ""}`}
                />
                Sincronizar
              </button>
            </>
          )}
        </>
      ) : (
        <>
          <CloudOff className="w-4 h-4 text-orange-600" />
          <span className="text-orange-600">Sin conexión</span>
        </>
      )}
    </div>
  );
}
