'use client';

import { useState, useTransition } from 'react';
import { Button } from '@/components/ui/button';
import { RefreshCw } from 'lucide-react';
import { triggerPolicySync } from '@/lib/actions/policySettings';
import { toast } from 'sonner';

export function SyncButton() {
  const [isPending, startTransition] = useTransition();

  const handleSync = () => {
    startTransition(async () => {
      try {
        const result = await triggerPolicySync();
        
        if (result.success) {
          toast.success(result.message ?? 'Policy sync triggered successfully');
        } else {
          toast.error(result.error ?? 'Failed to trigger sync');
        }
      } catch (error) {
        toast.error('An unexpected error occurred');
      }
    });
  };

  return (
    <Button
      onClick={handleSync}
      disabled={isPending}
      variant="default"
      size="default"
    >
      {isPending ? (
        <>
          <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
          Syncing...
        </>
      ) : (
        <>
          <RefreshCw className="mr-2 h-4 w-4" />
          Sync Policies
        </>
      )}
    </Button>
  );
}
