'use client';

import { useCallback } from 'react';

import { DeleteDialog } from '@/app/components/ui/dialog/delete-dialog';
import { toast } from '@/app/hooks/use-toast';
import { useT } from '@/lib/i18n/client';

import { useRevokeApiKey } from '../hooks/use-api-keys';
import type { ApiKey } from '../types';

interface ApiKeyRevokeDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  apiKey: ApiKey;
  organizationId: string;
  onSuccess?: () => void;
}

export function ApiKeyRevokeDialog({
  open,
  onOpenChange,
  apiKey,
  organizationId,
  onSuccess,
}: ApiKeyRevokeDialogProps) {
  const { t: tSettings } = useT('settings');
  const { mutate: revokeKey, isPending: isRevoking } =
    useRevokeApiKey(organizationId);

  const handleConfirm = useCallback(() => {
    if (isRevoking) return;

    revokeKey(apiKey.id, {
      onSuccess: () => {
        toast({
          title: tSettings('apiKeys.keyRevoked'),
        });
        onOpenChange(false);
        onSuccess?.();
      },
      onError: (error) => {
        console.error(error);
        toast({
          title: tSettings('apiKeys.keyRevokeFailed'),
          variant: 'destructive',
        });
      },
    });
  }, [isRevoking, revokeKey, apiKey.id, tSettings, onOpenChange, onSuccess]);

  return (
    <DeleteDialog
      open={open}
      onOpenChange={onOpenChange}
      title={tSettings('apiKeys.revokeKeyTitle')}
      description={tSettings('apiKeys.revokeConfirmation', {
        keyName: apiKey.name || '-',
      })}
      deleteText={tSettings('apiKeys.revokeKey')}
      isDeleting={isRevoking}
      onDelete={handleConfirm}
    />
  );
}
