/**
 * OrgStripeKeysForm Component
 * Allows organization owners/admins to configure their Stripe API keys
 * for accepting payments from their customers.
 */

"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";
import {
  CreditCard,
  Key,
  Eye,
  EyeOff,
  CheckCircle,
  AlertCircle,
  Trash2,
  Save,
  ExternalLink,
  Shield,
  Loader2,
  Info,
  AlertTriangle,
} from "lucide-react";

interface ExistingKeys {
  hasKeys: boolean;
  mode: "test" | "live" | null;
  configuredAt: string | null;
  maskedSecretKey: string | null;
  maskedWebhookSecret: string | null;
  publishableKey: string | null;
  canManageStripe: boolean;
  role: string | null;
}

interface ValidationResult {
  valid: boolean;
  mode: "test" | "live" | null;
  message: string;
  accountName?: string;
  accountEmail?: string;
}

interface OrgStripeKeysFormProps {
  lang: Lang;
}

export default function OrgStripeKeysForm({ lang }: OrgStripeKeysFormProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";

  // Translations
  const t = {
    title: isAr ? "إعدادات Stripe للدفع" : "Stripe Payment Settings",
    subtitle: isAr
      ? "قم بتكوين مفاتيح API الخاصة بك لقبول المدفوعات"
      : "Configure your API keys to accept payments from your customers",
    securityNote: isAr
      ? "جميع مفاتيح API مشفرة باستخدام تشفير AES-256-GCM قبل التخزين. فقط مالكي ومديري المؤسسة يمكنهم تكوين إعدادات Stripe."
      : "All API keys are encrypted using AES-256-GCM encryption before storage. Only organization owners and admins can configure Stripe settings.",
    currentConfig: isAr ? "التكوين الحالي" : "Current Configuration",
    activeKeys: isAr ? "مفاتيح API النشطة" : "Active Stripe API keys",
    mode: isAr ? "الوضع" : "Mode",
    liveMode: isAr ? "وضع مباشر" : "Live Mode",
    testMode: isAr ? "وضع اختبار" : "Test Mode",
    configured: isAr ? "تم التكوين" : "Configured",
    secretKey: isAr ? "المفتاح السري" : "Secret Key",
    publishableKey: isAr ? "المفتاح العام" : "Publishable Key",
    webhookSecret: isAr ? "سر الـ Webhook" : "Webhook Secret",
    optional: isAr ? "اختياري" : "Optional",
    updateKeys: isAr ? "تحديث المفاتيح" : "Update Keys",
    configureKeys: isAr ? "تكوين المفاتيح" : "Configure Keys",
    enterCredentials: isAr
      ? "أدخل بيانات اعتماد Stripe API الخاصة بك لتفعيل معالجة الدفع"
      : "Enter your Stripe API credentials to enable payment processing",
    secretKeyHint: isAr
      ? "يبدأ بـ sk_test_ (وضع اختبار) أو sk_live_ (وضع مباشر)"
      : "Starts with sk_test_ (test mode) or sk_live_ (live mode)",
    publishableKeyHint: isAr
      ? "يبدأ بـ pk_test_ (وضع اختبار) أو pk_live_ (وضع مباشر)"
      : "Starts with pk_test_ (test mode) or pk_live_ (live mode)",
    webhookHint: isAr
      ? "مطلوب للتحقق من الـ webhook. يبدأ بـ whsec_"
      : "Required for webhook verification. Starts with whsec_",
    validateKeys: isAr ? "التحقق من المفاتيح" : "Validate Keys",
    validating: isAr ? "جاري التحقق..." : "Validating...",
    saveKeys: isAr ? "حفظ المفاتيح" : "Save Keys",
    saving: isAr ? "جاري الحفظ..." : "Saving...",
    removeKeys: isAr ? "إزالة المفاتيح" : "Remove Keys",
    keysValid: isAr ? "المفاتيح صالحة" : "Keys Valid",
    validationFailed: isAr ? "فشل التحقق" : "Validation Failed",
    account: isAr ? "الحساب" : "Account",
    email: isAr ? "البريد الإلكتروني" : "Email",
    howToGet: isAr
      ? "كيفية الحصول على مفاتيح Stripe API"
      : "How to Get Your Stripe API Keys",
    step1: isAr
      ? "سجل الدخول إلى لوحة تحكم Stripe"
      : "Log in to your Stripe Dashboard",
    step2: isAr
      ? 'انقر على "المطورون" في القائمة العلوية'
      : 'Click on "Developers" in the top menu',
    step3: isAr
      ? 'اختر "مفاتيح API" من الشريط الجانبي'
      : 'Select "API keys" from the sidebar',
    step4: isAr
      ? 'انسخ "المفتاح السري" و "المفتاح العام"'
      : 'Copy the "Secret key" and "Publishable key"',
    step5: isAr
      ? 'للـ webhooks، انتقل إلى "Webhooks" وانسخ "Signing secret"'
      : 'For webhooks, go to "Webhooks" and copy the "Signing secret"',
    openStripeDashboard: isAr
      ? "فتح لوحة تحكم Stripe"
      : "Open Stripe Dashboard",
    loading: isAr ? "جاري التحميل..." : "Loading...",
    noPermission: isAr
      ? "ليس لديك صلاحية لإدارة إعدادات الدفع"
      : "You don't have permission to manage payment settings",
    noPermissionDesc: isAr
      ? "فقط مالكي ومديري المؤسسة يمكنهم تكوين مفاتيح Stripe."
      : "Only organization owners and admins can configure Stripe keys.",
    noOrganization: isAr ? "لم يتم العثور على مؤسسة" : "No Organization Found",
    noOrganizationDesc: isAr
      ? "يرجى إكمال إعداد حسابك أولاً."
      : "Please complete your account setup first.",
    confirmDelete: isAr
      ? "هل أنت متأكد أنك تريد إزالة مفاتيح Stripe؟ سيؤدي هذا إلى تعطيل معالجة الدفع."
      : "Are you sure you want to remove Stripe keys? This will disable payment processing.",
    keysRequired: isAr
      ? "المفتاح السري والمفتاح العام مطلوبان"
      : "Secret key and publishable key are required",
    invalidSecretKey: isAr
      ? 'تنسيق المفتاح السري غير صالح. يجب أن يبدأ بـ "sk_"'
      : 'Invalid secret key format. Must start with "sk_"',
    invalidPublishableKey: isAr
      ? 'تنسيق المفتاح العام غير صالح. يجب أن يبدأ بـ "pk_"'
      : 'Invalid publishable key format. Must start with "pk_"',
    pleaseValidate: isAr
      ? "يرجى التحقق من المفاتيح قبل الحفظ"
      : "Please validate keys before saving",
    cannotSaveInvalid: isAr
      ? "لا يمكن حفظ مفاتيح غير صالحة"
      : "Cannot save invalid keys",
    keysSaved: isAr
      ? "تم حفظ مفاتيح Stripe بنجاح!"
      : "Stripe keys saved successfully!",
    keysRemoved: isAr
      ? "تم إزالة مفاتيح Stripe بنجاح"
      : "Stripe keys removed successfully",
    liveWarning: isAr
      ? "أنت على وشك حفظ مفاتيح الوضع المباشر. سيتم معالجة المدفوعات الحقيقية."
      : "You're about to save LIVE mode keys. Real payments will be processed.",
    testNote: isAr
      ? "أنت في وضع الاختبار. لن يتم معالجة مدفوعات حقيقية."
      : "You're in test mode. No real payments will be processed.",
  };

  // Input values
  const [secretKey, setSecretKey] = useState("");
  const [publishableKey, setPublishableKey] = useState("");
  const [webhookSecret, setWebhookSecret] = useState("");

  // Visibility toggles
  const [showSecretKey, setShowSecretKey] = useState(false);
  const [showWebhookSecret, setShowWebhookSecret] = useState(false);

  // State
  const [existingKeys, setExistingKeys] = useState<ExistingKeys | null>(null);
  const [validationResult, setValidationResult] =
    useState<ValidationResult | null>(null);
  const [loading, setLoading] = useState(true);
  const [validating, setValidating] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [noOrganization, setNoOrganization] = useState(false);

  // Track if keys are validated
  const [isValidated, setIsValidated] = useState(false);

  // Fetch existing keys on mount
  useEffect(() => {
    fetchExistingKeys();
  }, []);

  const fetchExistingKeys = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch("/api/settings/stripe-keys");

      if (response.ok) {
        const data = await response.json();
        setExistingKeys(data);
        setNoOrganization(false);

        // If keys exist, populate publishable key
        if (data.hasKeys && data.publishableKey) {
          setPublishableKey(data.publishableKey);
        }
      } else {
        const errorData = await response.json();
        if (errorData.error === "No organization found") {
          setNoOrganization(true);
        } else {
          setError(errorData.error || "Failed to fetch existing keys");
        }
      }
    } catch (err) {
      console.error("Failed to fetch existing keys:", err);
      setError("Failed to fetch existing keys");
    } finally {
      setLoading(false);
    }
  };

  const handleValidate = async () => {
    // Reset previous validation
    setValidationResult(null);
    setError(null);
    setIsValidated(false);

    // Validation
    if (!secretKey.trim() || !publishableKey.trim()) {
      setError(t.keysRequired);
      return;
    }

    // Check key format
    if (!secretKey.startsWith("sk_")) {
      setError(t.invalidSecretKey);
      return;
    }

    if (!publishableKey.startsWith("pk_")) {
      setError(t.invalidPublishableKey);
      return;
    }

    try {
      setValidating(true);
      const response = await fetch("/api/settings/stripe-keys/validate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          secretKey: secretKey.trim(),
          publishableKey: publishableKey.trim(),
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setValidationResult({
          valid: data.valid,
          mode: data.mode,
          message: data.valid
            ? data.mode === "live"
              ? t.liveWarning
              : t.testNote
            : data.error || t.validationFailed,
          accountName: data.accountName,
        });
        setIsValidated(data.valid);
        if (!data.valid) {
          setError(data.error || t.validationFailed);
        }
      } else {
        setError(data.error || "Validation request failed");
        setValidationResult({
          valid: false,
          mode: null,
          message: data.error || t.validationFailed,
        });
      }
    } catch (err: any) {
      console.error("Validation error:", err);
      setError(err.message || "Failed to validate keys");
      setValidationResult({
        valid: false,
        mode: null,
        message: "Network error during validation",
      });
    } finally {
      setValidating(false);
    }
  };

  const handleSave = async () => {
    if (!isValidated) {
      setError(t.pleaseValidate);
      return;
    }

    if (!validationResult?.valid) {
      setError(t.cannotSaveInvalid);
      return;
    }

    // Confirmation for live mode
    if (validationResult.mode === "live") {
      if (!confirm(t.liveWarning)) {
        return;
      }
    }

    try {
      setSaving(true);
      setError(null);

      const response = await fetch("/api/settings/stripe-keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          secretKey: secretKey.trim(),
          publishableKey: publishableKey.trim(),
          webhookSecret: webhookSecret.trim() || undefined,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        alert(t.keysSaved);
        setSecretKey("");
        setWebhookSecret("");
        setValidationResult(null);
        setIsValidated(false);
        await fetchExistingKeys();
      } else {
        setError(data.error || "Failed to save keys");
      }
    } catch (err: any) {
      console.error("Save error:", err);
      setError(err.message || "Failed to save keys");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!confirm(t.confirmDelete)) {
      return;
    }

    try {
      setSaving(true);
      setError(null);

      const response = await fetch("/api/settings/stripe-keys", {
        method: "DELETE",
      });

      if (response.ok) {
        alert(t.keysRemoved);
        setSecretKey("");
        setPublishableKey("");
        setWebhookSecret("");
        setValidationResult(null);
        setIsValidated(false);
        await fetchExistingKeys();
      } else {
        const data = await response.json();
        setError(data.error || "Failed to remove keys");
      }
    } catch (err: any) {
      console.error("Delete error:", err);
      setError(err.message || "Failed to remove keys");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-2xl border border-slate-200 p-8">
        <div className="flex items-center justify-center">
          <Loader2 className="h-8 w-8 animate-spin text-brand-green" />
          <span className={`${isAr ? "mr-3" : "ml-3"} text-slate-600`}>
            {t.loading}
          </span>
        </div>
      </div>
    );
  }

  // No organization found
  if (noOrganization) {
    return (
      <div className="bg-white rounded-2xl border border-slate-200 p-8">
        <div className="flex flex-col items-center justify-center text-center py-8">
          <div className="w-16 h-16 rounded-full bg-amber-100 flex items-center justify-center mb-4">
            <AlertTriangle className="w-8 h-8 text-amber-600" />
          </div>
          <h3 className="text-lg font-semibold text-slate-900 mb-2">
            {t.noOrganization}
          </h3>
          <p className="text-sm text-slate-500 max-w-md">
            {t.noOrganizationDesc}
          </p>
        </div>
      </div>
    );
  }

  // User doesn't have permission
  if (existingKeys && !existingKeys.canManageStripe) {
    return (
      <div className="bg-white rounded-2xl border border-slate-200 p-8">
        <div className="flex flex-col items-center justify-center text-center py-8">
          <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
            <Shield className="w-8 h-8 text-slate-400" />
          </div>
          <h3 className="text-lg font-semibold text-slate-900 mb-2">
            {t.noPermission}
          </h3>
          <p className="text-sm text-slate-500 max-w-md">
            {t.noPermissionDesc}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6" dir={dir}>
      {/* Header */}
      <div>
        <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
        <p className="text-slate-600 mt-1">{t.subtitle}</p>
      </div>

      {/* Info Banner */}
      <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
        <div
          className={`flex items-start gap-3 ${isAr ? "flex-row-reverse" : ""}`}
        >
          <Shield className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" />
          <div>
            <h4 className="font-semibold text-blue-900 mb-1">
              {isAr ? "تشفير آمن" : "Secure Encryption"}
            </h4>
            <p className="text-sm text-blue-800">{t.securityNote}</p>
          </div>
        </div>
      </div>

      {/* Existing Keys Display */}
      {existingKeys?.hasKeys && (
        <div className="bg-white rounded-2xl border border-slate-200 p-6">
          <div
            className={`flex items-center gap-3 mb-4 ${isAr ? "flex-row-reverse" : ""}`}
          >
            <CreditCard className="w-6 h-6 text-brand-green" />
            <div>
              <h3 className="text-lg font-bold text-slate-900">
                {t.currentConfig}
              </h3>
              <p className="text-sm text-slate-600">{t.activeKeys}</p>
            </div>
          </div>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.mode}
                </label>
                <span
                  className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                    existingKeys.mode === "live"
                      ? "bg-green-100 text-green-800"
                      : "bg-yellow-100 text-yellow-800"
                  }`}
                >
                  {existingKeys.mode === "live" ? t.liveMode : t.testMode}
                </span>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.configured}
                </label>
                <p className="text-base text-slate-900">
                  {existingKeys.configuredAt
                    ? new Date(existingKeys.configuredAt).toLocaleDateString(
                        isAr ? "ar-SA" : "en-US",
                      )
                    : "--"}
                </p>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">
                {t.secretKey}
              </label>
              <code className="block text-sm bg-slate-100 px-3 py-2 rounded-lg border border-slate-200">
                {existingKeys.maskedSecretKey || "••••••••"}
              </code>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">
                {t.publishableKey}
              </label>
              <code className="block text-sm bg-slate-100 px-3 py-2 rounded-lg border border-slate-200">
                {existingKeys.publishableKey || "••••••••"}
              </code>
            </div>

            {existingKeys.maskedWebhookSecret && (
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.webhookSecret}
                </label>
                <code className="block text-sm bg-slate-100 px-3 py-2 rounded-lg border border-slate-200">
                  {existingKeys.maskedWebhookSecret}
                </code>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Configuration Form */}
      <div className="bg-white rounded-2xl border border-slate-200 p-6">
        <div
          className={`flex items-center gap-3 mb-6 ${isAr ? "flex-row-reverse" : ""}`}
        >
          <Key className="w-6 h-6 text-brand-green" />
          <div>
            <h3 className="text-lg font-bold text-slate-900">
              {existingKeys?.hasKeys ? t.updateKeys : t.configureKeys}
            </h3>
            <p className="text-sm text-slate-600">{t.enterCredentials}</p>
          </div>
        </div>

        <div className="space-y-5">
          {/* Secret Key */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.secretKey} <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type={showSecretKey ? "text" : "password"}
                value={secretKey}
                onChange={(e) => {
                  setSecretKey(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="sk_test_... or sk_live_..."
                className={`w-full px-4 py-2.5 ${isAr ? "pl-12" : "pr-12"} border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-brand-green transition-colors`}
                dir="ltr"
              />
              <button
                type="button"
                onClick={() => setShowSecretKey(!showSecretKey)}
                className={`absolute ${isAr ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600`}
              >
                {showSecretKey ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
            <p className="text-xs text-slate-500 mt-1">{t.secretKeyHint}</p>
          </div>

          {/* Publishable Key */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.publishableKey} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={publishableKey}
              onChange={(e) => {
                setPublishableKey(e.target.value);
                setValidationResult(null);
                setIsValidated(false);
              }}
              placeholder="pk_test_... or pk_live_..."
              className="w-full px-4 py-2.5 border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-brand-green transition-colors"
              dir="ltr"
            />
            <p className="text-xs text-slate-500 mt-1">
              {t.publishableKeyHint}
            </p>
          </div>

          {/* Webhook Secret */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.webhookSecret}{" "}
              <span className="text-slate-500">({t.optional})</span>
            </label>
            <div className="relative">
              <input
                type={showWebhookSecret ? "text" : "password"}
                value={webhookSecret}
                onChange={(e) => {
                  setWebhookSecret(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="whsec_..."
                className={`w-full px-4 py-2.5 ${isAr ? "pl-12" : "pr-12"} border-2 border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-brand-green transition-colors`}
                dir="ltr"
              />
              <button
                type="button"
                onClick={() => setShowWebhookSecret(!showWebhookSecret)}
                className={`absolute ${isAr ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600`}
              >
                {showWebhookSecret ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
            <p className="text-xs text-slate-500 mt-1">{t.webhookHint}</p>
          </div>

          {/* Validation Result */}
          {validationResult && (
            <div
              className={`p-4 rounded-xl border-2 ${
                validationResult.valid
                  ? validationResult.mode === "live"
                    ? "bg-amber-50 border-amber-200"
                    : "bg-green-50 border-green-200"
                  : "bg-red-50 border-red-200"
              }`}
            >
              <div
                className={`flex items-start gap-3 ${isAr ? "flex-row-reverse" : ""}`}
              >
                {validationResult.valid ? (
                  validationResult.mode === "live" ? (
                    <AlertTriangle className="w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0" />
                  ) : (
                    <CheckCircle className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
                  )
                ) : (
                  <AlertCircle className="w-5 h-5 text-red-600 mt-0.5 flex-shrink-0" />
                )}
                <div className="flex-1">
                  <p
                    className={`font-semibold ${
                      validationResult.valid
                        ? validationResult.mode === "live"
                          ? "text-amber-900"
                          : "text-green-900"
                        : "text-red-900"
                    }`}
                  >
                    {validationResult.valid ? t.keysValid : t.validationFailed}
                  </p>
                  <p
                    className={`text-sm mt-1 ${
                      validationResult.valid
                        ? validationResult.mode === "live"
                          ? "text-amber-800"
                          : "text-green-800"
                        : "text-red-800"
                    }`}
                  >
                    {validationResult.message}
                  </p>
                  {validationResult.valid && validationResult.accountName && (
                    <div
                      className={`mt-2 text-sm ${validationResult.mode === "live" ? "text-amber-800" : "text-green-800"}`}
                    >
                      <p>
                        <strong>{t.account}:</strong>{" "}
                        {validationResult.accountName}
                      </p>
                      <p>
                        <strong>{t.mode}:</strong>{" "}
                        <span
                          className={`font-semibold ${validationResult.mode === "live" ? "text-amber-700" : "text-green-700"}`}
                        >
                          {validationResult.mode === "live"
                            ? t.liveMode
                            : t.testMode}
                        </span>
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Error Display */}
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-3 text-sm text-red-700">
              {error}
            </div>
          )}

          {/* Action Buttons */}
          <div
            className={`flex items-center gap-3 pt-4 ${isAr ? "flex-row-reverse" : ""}`}
          >
            <button
              onClick={handleValidate}
              disabled={
                validating || !secretKey.trim() || !publishableKey.trim()
              }
              className={`flex items-center gap-2 px-6 py-2.5 bg-blue-600 text-white font-semibold rounded-xl hover:bg-blue-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed ${isAr ? "flex-row-reverse" : ""}`}
            >
              <Key className="w-4 h-4" />
              {validating ? t.validating : t.validateKeys}
            </button>

            <button
              onClick={handleSave}
              disabled={saving || !isValidated || !validationResult?.valid}
              className={`flex items-center gap-2 px-6 py-2.5 bg-brand-green text-white font-semibold rounded-xl hover:bg-green-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed ${isAr ? "flex-row-reverse" : ""}`}
            >
              <Save className="w-4 h-4" />
              {saving ? t.saving : t.saveKeys}
            </button>

            {existingKeys?.hasKeys && existingKeys.role === "OWNER" && (
              <button
                onClick={handleDelete}
                disabled={saving}
                className={`flex items-center gap-2 px-6 py-2.5 bg-red-600 text-white font-semibold rounded-xl hover:bg-red-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed ${isAr ? "flex-row-reverse mr-auto" : "ml-auto"}`}
              >
                <Trash2 className="w-4 h-4" />
                {t.removeKeys}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Help Section */}
      <div className="bg-slate-50 border border-slate-200 rounded-xl p-6">
        <h4 className="font-semibold text-slate-900 mb-3">{t.howToGet}</h4>
        <ol
          className={`list-decimal ${isAr ? "list-inside" : "list-inside"} space-y-2 text-sm text-slate-700 mb-4`}
        >
          <li>{t.step1}</li>
          <li>{t.step2}</li>
          <li>{t.step3}</li>
          <li>{t.step4}</li>
          <li>{t.step5}</li>
        </ol>
        <a
          href="https://dashboard.stripe.com/apikeys"
          target="_blank"
          rel="noopener noreferrer"
          className={`inline-flex items-center gap-2 text-brand-green hover:text-green-700 font-medium ${isAr ? "flex-row-reverse" : ""}`}
        >
          <ExternalLink className="w-4 h-4" />
          {t.openStripeDashboard}
        </a>
      </div>
    </div>
  );
}
