"use client";

import React, { useEffect, useState } from "react";
import { WifiOff, RefreshCw } from "lucide-react";
import { cn } from "@/lib/utils";

interface OfflineBannerProps {
  onSync?: () => void;
  isSyncing?: boolean;
  className?: string;
}

export function OfflineBanner({
  onSync,
  isSyncing = false,
  className,
}: OfflineBannerProps) {
  const [isOffline, setIsOffline] = useState(false);

  useEffect(() => {
    // Initial check
    if (typeof window !== "undefined") {
      setIsOffline(!navigator.onLine);
    }

    const handleOnline = () => setIsOffline(false);
    const handleOffline = () => setIsOffline(true);

    window.addEventListener("online", handleOnline);
    window.addEventListener("offline", handleOffline);

    return () => {
      window.removeEventListener("online", handleOnline);
      window.removeEventListener("offline", handleOffline);
    };
  }, []);

  if (!isOffline) {
    return null;
  }

  return (
    <div
      role="status"
      className={cn(
        "bg-amber-500 text-white text-xs px-4 py-2 flex items-center justify-between shadow-sm transition-all animate-in slide-in-from-top",
        className
      )}
    >
      <div className="flex items-center gap-2 font-medium">
        <WifiOff className="w-4 h-4 shrink-0" />
        <span>
          Offline Mode — Device connection lost. Attendance marks are saving locally on your device.
        </span>
      </div>

      {onSync && (
        <button
          type="button"
          onClick={onSync}
          disabled={isSyncing}
          className="px-2.5 py-1 bg-amber-600 hover:bg-amber-700 disabled:opacity-50 text-[11px] font-semibold rounded flex items-center gap-1 transition-colors ml-4 shrink-0"
        >
          <RefreshCw className={cn("w-3 h-3", isSyncing && "animate-spin")} />
          Sync Draft
        </button>
      )}
    </div>
  );
}
