'use client';

import { useTranslations } from 'next-intl';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';

interface SyncStatusProps {
  lastSync?: Date;
  locale?: string;
  error?: string;
  onSync?: () => void;
  isSyncing?: boolean;
  className?: string;
}

/**
 * Display the last sync time and optional sync button
 */
export function SyncStatus({
  lastSync,
  locale = 'de',
  error,
  onSync,
  isSyncing = false,
  className,
}: SyncStatusProps) {
  const t = useTranslations('integrations');
  const dateLocale = locale === 'de' ? de : enUS;

  const formattedTime = lastSync
    ? formatDistanceToNow(lastSync, { addSuffix: true, locale: dateLocale })
    : null;

  return (
    <div className={cn('flex items-center justify-between text-sm', className)}>
      <div className="flex items-center gap-2 text-muted-foreground">
        {error ? (
          <AlertTriangle className="h-4 w-4 text-destructive" />
        ) : (
          <Clock className="h-4 w-4" />
        )}
        <span>
          {t('lastSync')}: {formattedTime || t('never')}
        </span>
      </div>

      {onSync && (
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={onSync}
              disabled={isSyncing}
            >
              <RefreshCw
                className={cn('h-4 w-4', isSyncing && 'animate-spin')}
              />
            </Button>
          </TooltipTrigger>
          <TooltipContent>{t('syncNow')}</TooltipContent>
        </Tooltip>
      )}
    </div>
  );
}
