'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Loader2, CheckCircle, XCircle, RefreshCw } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/use-toast';
import { useTestConnection } from '@/hooks/integrations';
import type { IntegrationType } from '@/types/integrations';

interface ConnectionTestButtonProps {
  integrationType: IntegrationType;
  disabled?: boolean;
  className?: string;
  variant?: 'default' | 'outline' | 'ghost';
  size?: 'default' | 'sm' | 'lg' | 'icon';
}

/**
 * Button to test integration connection with loading and result states
 */
export function ConnectionTestButton({
  integrationType,
  disabled = false,
  className,
  variant = 'outline',
  size = 'sm',
}: ConnectionTestButtonProps) {
  const t = useTranslations('integrations');
  const { toast } = useToast();
  const testConnection = useTestConnection();
  const [lastResult, setLastResult] = useState<'success' | 'error' | null>(null);

  const handleTest = async () => {
    setLastResult(null);

    try {
      const result = await testConnection.mutateAsync(integrationType);
      setLastResult(result.success ? 'success' : 'error');

      toast({
        title: result.success ? t('testSuccess') : t('testFailed'),
        description: result.message,
        variant: result.success ? 'default' : 'destructive',
      });

      // Reset result after 3 seconds
      setTimeout(() => setLastResult(null), 3000);
    } catch {
      setLastResult('error');
      toast({
        title: t('testFailed'),
        description: t('testError'),
        variant: 'destructive',
      });
      setTimeout(() => setLastResult(null), 3000);
    }
  };

  const isLoading = testConnection.isPending;

  return (
    <Button
      variant={variant}
      size={size}
      onClick={handleTest}
      disabled={disabled || isLoading}
      className={cn(
        lastResult === 'success' && 'border-green-500 text-green-500',
        lastResult === 'error' && 'border-destructive text-destructive',
        className
      )}
    >
      {isLoading ? (
        <>
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          {t('testing')}
        </>
      ) : lastResult === 'success' ? (
        <>
          <CheckCircle className="mr-2 h-4 w-4" />
          {t('testSuccess')}
        </>
      ) : lastResult === 'error' ? (
        <>
          <XCircle className="mr-2 h-4 w-4" />
          {t('testFailed')}
        </>
      ) : (
        <>
          <RefreshCw className="mr-2 h-4 w-4" />
          {t('test')}
        </>
      )}
    </Button>
  );
}
