import { formatDistanceToNow } from 'date-fns';
import { Clock, Zap } from 'lucide-react';

import { Badge } from '@/Components/ui/badge';

interface SyncStatusIndicatorProps {
  lastWebhookAt: string | null;
  lastPeriodicSyncAt: string | null;
  isConnected: boolean;
}

export function SyncStatusIndicator({
  lastWebhookAt,
  lastPeriodicSyncAt,
  isConnected,
}: SyncStatusIndicatorProps) {
  if (!isConnected) {
    return (
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <Clock className="h-4 w-4" />
        <span>Not connected</span>
      </div>
    );
  }

  // Determine if real-time sync is active (webhook more recent than periodic)
  const webhookTime = lastWebhookAt ? new Date(lastWebhookAt).getTime() : 0;
  const periodicTime = lastPeriodicSyncAt ? new Date(lastPeriodicSyncAt).getTime() : 0;
  const isRealTime = webhookTime > periodicTime && lastWebhookAt !== null;

  const lastSyncTime = isRealTime ? lastWebhookAt : lastPeriodicSyncAt;

  return (
    <div className="flex items-center gap-2 text-sm">
      {isRealTime ? (
        <Badge variant="success" className="flex items-center gap-1">
          <Zap className="h-3 w-3" />
          Real-time sync
        </Badge>
      ) : (
        <Badge variant="secondary" className="flex items-center gap-1">
          <Clock className="h-3 w-3" />
          Periodic sync
        </Badge>
      )}
      {lastSyncTime && (
        <span className="text-muted-foreground">
          Last synced {formatDistanceToNow(new Date(lastSyncTime), { addSuffix: true })}
        </span>
      )}
    </div>
  );
}
