'use client';

import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface Credential {
  id: string;
  name: string;
  username: string;
  authType: 'password' | 'ssh_key' | 'ssh_key_with_passphrase';
  description: string;
  associatedServers: number;
  createdAt: string;
  updatedAt: string;
}

type CredentialsResponse = Credential[];

interface CredentialFormData {
  name: string;
  username: string;
  authType: 'password' | 'ssh_key' | 'ssh_key_with_passphrase';
  password: string;
  privateKey: string;
  passphrase: string;
  description: string;
}

interface EditFormData {
  name: string;
  description: string;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const AUTH_TYPE_LABEL_KEYS: Record<Credential['authType'], string> = {
  password: 'credentials.authTypes.password',
  ssh_key: 'credentials.authTypes.sshKey',
  ssh_key_with_passphrase: 'credentials.authTypes.sshKeyPassphrase',
};

const EMPTY_FORM: CredentialFormData = {
  name: '',
  username: '',
  authType: 'password',
  password: '',
  privateKey: '',
  passphrase: '',
  description: '',
};

const EMPTY_EDIT_FORM: EditFormData = {
  name: '',
  description: '',
};

// ---------------------------------------------------------------------------
// Auth type badge
// ---------------------------------------------------------------------------

function AuthTypeBadge({ authType }: { authType: Credential['authType'] }) {
  const { t } = useTranslation('security');
  const styles: Record<Credential['authType'], string> = {
    password: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    ssh_key: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    ssh_key_with_passphrase: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
  };

  return (
    <span
      className={cn(
        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
        styles[authType],
      )}
    >
      {t(AUTH_TYPE_LABEL_KEYS[authType])}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Add credential dialog
// ---------------------------------------------------------------------------

function AddCredentialDialog({
  open,
  form,
  errors,
  saving,
  onClose,
  onChange,
  onSubmit,
}: {
  open: boolean;
  form: CredentialFormData;
  errors: Partial<Record<keyof CredentialFormData, string>>;
  saving: boolean;
  onClose: () => void;
  onChange: (field: keyof CredentialFormData, value: string) => void;
  onSubmit: () => void;
}) {
  const { t } = useTranslation('security');
  const { t: tc } = useTranslation('common');
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      {/* dialog */}
      <div className="relative z-10 w-full max-w-lg bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-4">{t('credentials.addCredential')}</h2>

        <div className="space-y-4 max-h-[70vh] overflow-y-auto pr-1">
          {/* name */}
          <div>
            <label className="block text-sm font-medium mb-1">
              {t('credentials.form.name')} <span className="text-destructive">*</span>
            </label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => onChange('name', e.target.value)}
              className={cn(
                'w-full px-3 py-2 rounded-md border bg-background text-sm',
                errors.name ? 'border-destructive' : 'border-input',
              )}
              placeholder="Production SSH Key"
            />
            {errors.name && (
              <p className="text-xs text-destructive mt-1">{errors.name}</p>
            )}
          </div>

          {/* username */}
          <div>
            <label className="block text-sm font-medium mb-1">
              {t('credentials.form.username')} <span className="text-destructive">*</span>
            </label>
            <input
              type="text"
              value={form.username}
              onChange={(e) => onChange('username', e.target.value)}
              className={cn(
                'w-full px-3 py-2 rounded-md border bg-background text-sm',
                errors.username ? 'border-destructive' : 'border-input',
              )}
              placeholder="root"
            />
            {errors.username && (
              <p className="text-xs text-destructive mt-1">{errors.username}</p>
            )}
          </div>

          {/* auth type */}
          <div>
            <label className="block text-sm font-medium mb-1">{t('credentials.form.authType')}</label>
            <select
              value={form.authType}
              onChange={(e) => onChange('authType', e.target.value)}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm"
            >
              <option value="password">{t('credentials.authTypes.password')}</option>
              <option value="ssh_key">{t('credentials.authTypes.sshKey')}</option>
              <option value="ssh_key_with_passphrase">{t('credentials.authTypes.sshKeyPassphrase')}</option>
            </select>
          </div>

          {/* password field */}
          {form.authType === 'password' && (
            <div>
              <label className="block text-sm font-medium mb-1">
                {t('credentials.form.password')} <span className="text-destructive">*</span>
              </label>
              <input
                type="password"
                value={form.password}
                onChange={(e) => onChange('password', e.target.value)}
                className={cn(
                  'w-full px-3 py-2 rounded-md border bg-background text-sm',
                  errors.password ? 'border-destructive' : 'border-input',
                )}
                placeholder="Enter password"
              />
              {errors.password && (
                <p className="text-xs text-destructive mt-1">{errors.password}</p>
              )}
            </div>
          )}

          {/* private key field */}
          {(form.authType === 'ssh_key' || form.authType === 'ssh_key_with_passphrase') && (
            <div>
              <label className="block text-sm font-medium mb-1">
                {t('credentials.form.privateKey')} <span className="text-destructive">*</span>
              </label>
              <textarea
                value={form.privateKey}
                onChange={(e) => onChange('privateKey', e.target.value)}
                rows={6}
                className={cn(
                  'w-full px-3 py-2 rounded-md border bg-background text-sm font-mono resize-none',
                  errors.privateKey ? 'border-destructive' : 'border-input',
                )}
                placeholder="-----BEGIN RSA PRIVATE KEY-----"
              />
              {errors.privateKey && (
                <p className="text-xs text-destructive mt-1">{errors.privateKey}</p>
              )}
            </div>
          )}

          {/* passphrase field */}
          {form.authType === 'ssh_key_with_passphrase' && (
            <div>
              <label className="block text-sm font-medium mb-1">
                {t('credentials.form.passphrase')} <span className="text-destructive">*</span>
              </label>
              <input
                type="password"
                value={form.passphrase}
                onChange={(e) => onChange('passphrase', e.target.value)}
                className={cn(
                  'w-full px-3 py-2 rounded-md border bg-background text-sm',
                  errors.passphrase ? 'border-destructive' : 'border-input',
                )}
                placeholder="Enter passphrase"
              />
              {errors.passphrase && (
                <p className="text-xs text-destructive mt-1">{errors.passphrase}</p>
              )}
            </div>
          )}

          {/* description */}
          <div>
            <label className="block text-sm font-medium mb-1">{tc('description')}</label>
            <textarea
              value={form.description}
              onChange={(e) => onChange('description', e.target.value)}
              rows={3}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm resize-none"
              placeholder="Optional description..."
            />
          </div>
        </div>

        {/* actions */}
        <div className="flex justify-end gap-3 mt-6 pt-4 border-t">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={saving}
          >
            {tc('cancel')}
          </button>
          <button
            type="button"
            onClick={onSubmit}
            disabled={saving}
            className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
          >
            {saving ? tc('saving') : tc('save')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Edit credential dialog (name/description only)
// ---------------------------------------------------------------------------

function EditCredentialDialog({
  open,
  form,
  errors,
  saving,
  onClose,
  onChange,
  onSubmit,
}: {
  open: boolean;
  form: EditFormData;
  errors: Partial<Record<keyof EditFormData, string>>;
  saving: boolean;
  onClose: () => void;
  onChange: (field: keyof EditFormData, value: string) => void;
  onSubmit: () => void;
}) {
  const { t } = useTranslation('security');
  const { t: tc } = useTranslation('common');
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      {/* dialog */}
      <div className="relative z-10 w-full max-w-lg bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-4">{t('credentials.editCredential')}</h2>

        <p className="text-xs text-muted-foreground mb-4 p-3 bg-muted rounded-md">
          {t('credentials.encryptionWarning')}
        </p>

        <div className="space-y-4">
          {/* name */}
          <div>
            <label className="block text-sm font-medium mb-1">
              {t('credentials.form.name')} <span className="text-destructive">*</span>
            </label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => onChange('name', e.target.value)}
              className={cn(
                'w-full px-3 py-2 rounded-md border bg-background text-sm',
                errors.name ? 'border-destructive' : 'border-input',
              )}
              placeholder="Credential name"
            />
            {errors.name && (
              <p className="text-xs text-destructive mt-1">{errors.name}</p>
            )}
          </div>

          {/* description */}
          <div>
            <label className="block text-sm font-medium mb-1">{tc('description')}</label>
            <textarea
              value={form.description}
              onChange={(e) => onChange('description', e.target.value)}
              rows={3}
              className="w-full px-3 py-2 rounded-md border border-input bg-background text-sm resize-none"
              placeholder="Optional description..."
            />
          </div>
        </div>

        {/* actions */}
        <div className="flex justify-end gap-3 mt-6 pt-4 border-t">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={saving}
          >
            {tc('cancel')}
          </button>
          <button
            type="button"
            onClick={onSubmit}
            disabled={saving}
            className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
          >
            {saving ? tc('saving') : tc('save')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Delete confirmation dialog
// ---------------------------------------------------------------------------

function DeleteDialog({
  open,
  credentialName,
  associatedServers,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  credentialName: string;
  associatedServers: number;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('security');
  const { t: tc } = useTranslation('common');
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative z-10 w-full max-w-sm bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-2">{t('credentials.deleteCredential')}</h2>
        <p className="text-sm text-muted-foreground mb-4">
          {tc('confirmDelete')} <strong>{credentialName}</strong>
        </p>

        {associatedServers > 0 && (
          <div className="p-3 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-sm text-destructive">
            <strong>{tc('warning')}:</strong> This credential is currently associated with{' '}
            <strong>{associatedServers}</strong> server{associatedServers !== 1 ? 's' : ''}.
            Deleting it will remove the credential from those servers and may prevent SSH connections.
          </div>
        )}

        <div className="p-3 mb-4 rounded-md bg-muted text-xs text-muted-foreground">
          {t('credentials.encryptionWarning')}
        </div>

        <div className="flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={deleting}
          >
            {tc('cancel')}
          </button>
          <button
            onClick={onConfirm}
            disabled={deleting}
            className="px-4 py-2 text-sm rounded-md bg-destructive text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
          >
            {deleting ? tc('deleting') : tc('delete')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------

export default function CredentialsPage() {
  const { t } = useTranslation('security');
  const { t: tc } = useTranslation('common');
  const queryClient = useQueryClient();

  // State ----------------------------------------------------------------
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [editingCredential, setEditingCredential] = useState<Credential | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Credential | null>(null);
  const [form, setForm] = useState<CredentialFormData>({ ...EMPTY_FORM });
  const [editForm, setEditForm] = useState<EditFormData>({ ...EMPTY_EDIT_FORM });
  const [errors, setErrors] = useState<Partial<Record<keyof CredentialFormData, string>>>({});
  const [editErrors, setEditErrors] = useState<Partial<Record<keyof EditFormData, string>>>({});
  const [testingId, setTestingId] = useState<string | null>(null);
  const [testResults, setTestResults] = useState<Record<string, { success: boolean; message: string }>>({});

  // Queries --------------------------------------------------------------
  const { data, isLoading, error } = useQuery({
    queryKey: queryKeys.credentials.list(),
    queryFn: () =>
      apiClient<CredentialsResponse>('/api/v1/inventory/credentials'),
  });

  const credentials = Array.isArray(data) ? data : [];

  // Mutations ------------------------------------------------------------
  const createMutation = useMutation({
    mutationFn: (body: Record<string, unknown>) =>
      apiClient<Credential>('/api/v1/inventory/credentials', { method: 'POST', body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.credentials.all });
      closeAddDialog();
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, body }: { id: string; body: Record<string, unknown> }) =>
      apiClient<Credential>(`/api/v1/inventory/credentials/${id}`, { method: 'PUT', body }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.credentials.all });
      closeEditDialog();
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      apiClient<void>(`/api/v1/inventory/credentials/${id}`, { method: 'DELETE' }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.credentials.all });
      setDeleteTarget(null);
    },
  });

  const testMutation = useMutation({
    mutationFn: (id: string) =>
      apiClient<{ success: boolean; message: string }>(
        `/api/v1/inventory/credentials/${id}/test`,
        { method: 'POST' },
      ),
    onSuccess: (result, id) => {
      setTestResults((prev) => ({ ...prev, [id]: result }));
      setTestingId(null);
    },
    onError: (err: Error, id) => {
      setTestResults((prev) => ({
        ...prev,
        [id]: { success: false, message: err.message },
      }));
      setTestingId(null);
    },
  });

  // Helpers --------------------------------------------------------------
  const validateAdd = useCallback((): boolean => {
    const next: Partial<Record<keyof CredentialFormData, string>> = {};
    if (!form.name.trim()) next.name = 'Name is required';
    if (!form.username.trim()) next.username = 'Username is required';

    if (form.authType === 'password') {
      if (!form.password.trim()) next.password = 'Password is required';
    }
    if (form.authType === 'ssh_key' || form.authType === 'ssh_key_with_passphrase') {
      if (!form.privateKey.trim()) next.privateKey = 'Private key is required';
    }
    if (form.authType === 'ssh_key_with_passphrase') {
      if (!form.passphrase.trim()) next.passphrase = 'Passphrase is required';
    }

    setErrors(next);
    return Object.keys(next).length === 0;
  }, [form]);

  const validateEdit = useCallback((): boolean => {
    const next: Partial<Record<keyof EditFormData, string>> = {};
    if (!editForm.name.trim()) next.name = 'Name is required';
    setEditErrors(next);
    return Object.keys(next).length === 0;
  }, [editForm]);

  const closeAddDialog = useCallback(() => {
    setAddDialogOpen(false);
    setForm({ ...EMPTY_FORM });
    setErrors({});
  }, []);

  const closeEditDialog = useCallback(() => {
    setEditingCredential(null);
    setEditForm({ ...EMPTY_EDIT_FORM });
    setEditErrors({});
  }, []);

  const openAdd = useCallback(() => {
    setForm({ ...EMPTY_FORM });
    setErrors({});
    setAddDialogOpen(true);
  }, []);

  const openEdit = useCallback((credential: Credential) => {
    setEditingCredential(credential);
    setEditForm({
      name: credential.name,
      description: credential.description ?? '',
    });
    setEditErrors({});
  }, []);

  const handleAddChange = useCallback(
    (field: keyof CredentialFormData, value: string) => {
      setForm((prev) => ({ ...prev, [field]: value }));
      setErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    },
    [],
  );

  const handleEditChange = useCallback(
    (field: keyof EditFormData, value: string) => {
      setEditForm((prev) => ({ ...prev, [field]: value }));
      setEditErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    },
    [],
  );

  const handleAddSubmit = useCallback(() => {
    if (!validateAdd()) return;

    const body: Record<string, unknown> = {
      name: form.name.trim(),
      username: form.username.trim(),
      authType: form.authType,
      description: form.description.trim(),
    };

    if (form.authType === 'password') {
      body.password = form.password;
    }
    if (form.authType === 'ssh_key' || form.authType === 'ssh_key_with_passphrase') {
      body.privateKey = form.privateKey;
    }
    if (form.authType === 'ssh_key_with_passphrase') {
      body.passphrase = form.passphrase;
    }

    createMutation.mutate(body);
  }, [form, validateAdd, createMutation]);

  const handleEditSubmit = useCallback(() => {
    if (!validateEdit()) return;
    if (!editingCredential) return;

    const body: Record<string, unknown> = {
      name: editForm.name.trim(),
      description: editForm.description.trim(),
    };

    updateMutation.mutate({ id: editingCredential.id, body });
  }, [editForm, editingCredential, validateEdit, updateMutation]);

  const handleTestConnection = useCallback(
    (credential: Credential) => {
      setTestingId(credential.id);
      setTestResults((prev) => {
        const next = { ...prev };
        delete next[credential.id];
        return next;
      });
      testMutation.mutate(credential.id);
    },
    [testMutation],
  );

  const formatDate = useCallback((dateString: string) => {
    try {
      return new Date(dateString).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
      });
    } catch {
      return dateString;
    }
  }, []);

  const isAddSaving = createMutation.isPending;
  const isEditSaving = updateMutation.isPending;

  // Render ---------------------------------------------------------------
  return (
    <div>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold">{t('credentials.title')}</h1>
          <p className="text-sm text-muted-foreground mt-1">
            {t('credentials.subtitle')}
          </p>
        </div>
        <button
          onClick={openAdd}
          className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 whitespace-nowrap"
        >
          {t('credentials.addCredential')}
        </button>
      </div>

      {/* Security notice banner */}
      <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-6">
        <div className="flex items-start gap-3">
          <div className="flex-shrink-0 mt-0.5">
            <svg
              className="h-5 w-5 text-yellow-600 dark:text-yellow-400"
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
              <path d="M7 11V7a5 5 0 0 1 10 0v4" />
            </svg>
          </div>
          <p className="text-sm text-yellow-800 dark:text-yellow-200">
            {t('credentials.securityNotice')}
          </p>
        </div>
      </div>

      {/* Error state */}
      {error && (
        <div className="p-4 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('credentials.loadError')} {(error as Error).message}
        </div>
      )}

      {/* Loading state */}
      {isLoading && (
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('credentials.loading')}
        </div>
      )}

      {/* Data table */}
      {!isLoading && !error && (
        <div className="border rounded-lg overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/50">
                  <th className="text-left px-4 py-3 font-medium">{t('credentials.table.name')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('credentials.table.type')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('credentials.table.username')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('credentials.table.associatedServers')}</th>
                  <th className="text-left px-4 py-3 font-medium">{t('credentials.table.created')}</th>
                  <th className="text-right px-4 py-3 font-medium">{t('credentials.table.actions')}</th>
                </tr>
              </thead>
              <tbody>
                {credentials.length === 0 ? (
                  <tr>
                    <td
                      colSpan={6}
                      className="text-center text-muted-foreground py-12"
                    >
                      {t('credentials.empty')}
                    </td>
                  </tr>
                ) : (
                  credentials.map((credential) => (
                    <tr
                      key={credential.id}
                      className="border-b last:border-b-0 hover:bg-muted/30 transition-colors"
                    >
                      <td className="px-4 py-3">
                        <div>
                          <span className="font-medium">{credential.name}</span>
                          {credential.description && (
                            <p className="text-xs text-muted-foreground mt-0.5 truncate max-w-[200px]">
                              {credential.description}
                            </p>
                          )}
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <AuthTypeBadge authType={credential.authType} />
                      </td>
                      <td className="px-4 py-3 font-mono text-xs">
                        {credential.username}
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {credential.associatedServers} server{credential.associatedServers !== 1 ? 's' : ''}
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {formatDate(credential.createdAt)}
                      </td>
                      <td className="px-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-2">
                          {/* Test connection result */}
                          {testResults[credential.id] && (
                            <span
                              className={cn(
                                'text-xs px-2 py-0.5 rounded-full',
                                testResults[credential.id].success
                                  ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                                  : 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
                              )}
                              title={testResults[credential.id].message}
                            >
                              {testResults[credential.id].success ? 'OK' : 'Failed'}
                            </span>
                          )}
                          <button
                            onClick={() => handleTestConnection(credential)}
                            disabled={testingId === credential.id}
                            className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors disabled:opacity-50"
                          >
                            {testingId === credential.id ? 'Testing...' : t('credentials.testCredential')}
                          </button>
                          <button
                            onClick={() => openEdit(credential)}
                            className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                          >
                            {tc('edit')}
                          </button>
                          <button
                            onClick={() => setDeleteTarget(credential)}
                            className="px-3 py-1 text-xs rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 transition-colors"
                          >
                            {tc('delete')}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Add credential dialog */}
      <AddCredentialDialog
        open={addDialogOpen}
        form={form}
        errors={errors}
        saving={isAddSaving}
        onClose={closeAddDialog}
        onChange={handleAddChange}
        onSubmit={handleAddSubmit}
      />

      {/* Edit credential dialog */}
      <EditCredentialDialog
        open={!!editingCredential}
        form={editForm}
        errors={editErrors}
        saving={isEditSaving}
        onClose={closeEditDialog}
        onChange={handleEditChange}
        onSubmit={handleEditSubmit}
      />

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={!!deleteTarget}
        credentialName={deleteTarget?.name ?? ''}
        associatedServers={deleteTarget?.associatedServers ?? 0}
        deleting={deleteMutation.isPending}
        onClose={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
        }}
      />
    </div>
  );
}
