/**
 * OrgWhatsAppKeysForm Component
 *
 * Allows organization owners/admins to configure their WhatsApp Business API keys
 * for connecting their WhatsApp Business account.
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config/index";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  MessageCircle,
  Key,
  Eye,
  EyeOff,
  CheckCircle,
  AlertCircle,
  Trash2,
  Save,
  ExternalLink,
  Shield,
  Loader2,
  AlertTriangle,
  Copy,
  Check,
} from "lucide-react";

interface ExistingKeys {
  hasKeys: boolean;
  phoneNumberId: string | null;
  accessTokenMasked: string | null;
  appSecretMasked: string | null;
  displayNumber: string | null;
  verifyToken: string | null;
  webhookUrl: string | null;
  configuredAt: string | null;
  webhookVerified: boolean;
  canManageWhatsApp: boolean;
  role: string | null;
}

interface ValidationResult {
  valid: boolean;
  displayNumber?: string;
  businessName?: string;
  message: string;
}

interface OrgWhatsAppKeysFormProps {
  lang: Lang;
}

export default function OrgWhatsAppKeysForm({
  lang,
}: OrgWhatsAppKeysFormProps) {
  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";

  // Translations
  const t = {
    title: isAr ? "إعدادات WhatsApp Business" : "WhatsApp Business Settings",
    subtitle: isAr
      ? "قم بتوصيل حساب WhatsApp Business الخاص بك لتلقي الرسائل"
      : "Connect your WhatsApp Business account to receive messages",
    securityNote: isAr
      ? "جميع مفاتيح API مشفرة باستخدام تشفير AES-256-GCM قبل التخزين. فقط مالكي ومديري المؤسسة يمكنهم تكوين إعدادات WhatsApp."
      : "All API keys are encrypted using AES-256-GCM encryption before storage. Only organization owners and admins can configure WhatsApp settings.",
    currentConfig: isAr ? "التكوين الحالي" : "Current Configuration",
    connected: isAr ? "متصل" : "Connected",
    notConnected: isAr ? "غير متصل" : "Not Connected",
    phoneNumberId: isAr ? "معرف رقم الهاتف" : "Phone Number ID",
    accessToken: isAr ? "رمز الوصول" : "Access Token",
    appSecret: isAr ? "سر التطبيق" : "App Secret",
    displayNumber: isAr ? "رقم العرض" : "Display Number",
    optional: isAr ? "اختياري" : "Optional",
    webhookConfig: isAr ? "تكوين Webhook" : "Webhook Configuration",
    webhookUrl: isAr ? "عنوان Webhook" : "Webhook URL",
    verifyToken: isAr ? "رمز التحقق" : "Verify Token",
    webhookVerified: isAr ? "تم التحقق من Webhook" : "Webhook Verified",
    webhookPending: isAr ? "في انتظار التحقق" : "Verification Pending",
    configured: isAr ? "تم التكوين" : "Configured",
    updateKeys: isAr ? "تحديث المفاتيح" : "Update Keys",
    configureKeys: isAr ? "تكوين المفاتيح" : "Configure Keys",
    enterCredentials: isAr
      ? "أدخل بيانات اعتماد WhatsApp Business API لتفعيل استقبال الرسائل"
      : "Enter your WhatsApp Business API credentials to enable message receiving",
    phoneNumberIdHint: isAr
      ? "معرف رقم الهاتف من Meta Business Suite (أرقام فقط)"
      : "Phone Number ID from Meta Business Suite (numbers only)",
    accessTokenHint: isAr
      ? "رمز الوصول الدائم من تطبيق Meta الخاص بك (يبدأ بـ EAA)"
      : "Permanent Access Token from your Meta App (starts with EAA)",
    appSecretHint: isAr
      ? "سر التطبيق للتحقق من توقيع Webhook (سداسي عشري)"
      : "App Secret for webhook signature verification (hexadecimal)",
    displayNumberHint: isAr
      ? "رقم العرض الذي يراه العملاء (اختياري - يتم جلبه تلقائيًا)"
      : "Display number shown to customers (optional - auto-fetched)",
    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",
    businessName: isAr ? "اسم النشاط التجاري" : "Business Name",
    howToGet: isAr
      ? "كيفية الحصول على مفاتيح WhatsApp Business API"
      : "How to Get Your WhatsApp Business API Keys",
    step1: isAr
      ? "أنشئ تطبيق Meta للمطورين وأضف منتج WhatsApp"
      : "Create a Meta Developer App and add WhatsApp product",
    step2: isAr
      ? "انتقل إلى WhatsApp > Getting Started وانسخ Phone Number ID"
      : "Go to WhatsApp > Getting Started and copy the Phone Number ID",
    step3: isAr
      ? "أنشئ رمز وصول دائم من System Users"
      : "Create a Permanent Access Token from System Users",
    step4: isAr
      ? "انسخ App Secret من تطبيقك > Settings > Basic"
      : "Copy App Secret from your app > Settings > Basic",
    step5: isAr
      ? "الصق عنوان Webhook ورمز التحقق في Meta Developer Console"
      : "Paste the Webhook URL and Verify Token in Meta Developer Console",
    openMetaConsole: isAr
      ? "فتح Meta Developer Console"
      : "Open Meta Developer Console",
    loading: isAr ? "جاري التحميل..." : "Loading...",
    noPermission: isAr
      ? "ليس لديك صلاحية لإدارة إعدادات WhatsApp"
      : "You don't have permission to manage WhatsApp settings",
    noPermissionDesc: isAr
      ? "فقط مالكي ومديري المؤسسة يمكنهم تكوين مفاتيح WhatsApp."
      : "Only organization owners and admins can configure WhatsApp keys.",
    noOrganization: isAr ? "لم يتم العثور على مؤسسة" : "No Organization Found",
    noOrganizationDesc: isAr
      ? "يرجى إكمال إعداد حسابك أولاً."
      : "Please complete your account setup first.",
    confirmDelete: isAr
      ? "هل أنت متأكد أنك تريد إزالة مفاتيح WhatsApp؟ سيؤدي هذا إلى قطع اتصال WhatsApp."
      : "Are you sure you want to remove WhatsApp keys? This will disconnect WhatsApp.",
    keysRequired: isAr
      ? "معرف رقم الهاتف ورمز الوصول وسر التطبيق مطلوبة"
      : "Phone Number ID, Access Token, and App Secret are required",
    invalidPhoneNumberId: isAr
      ? "معرف رقم الهاتف يجب أن يكون أرقامًا فقط"
      : "Phone Number ID must be numbers only",
    invalidAccessToken: isAr
      ? "رمز الوصول يجب أن يبدأ بـ EAA"
      : "Access Token must start with EAA",
    invalidAppSecret: isAr
      ? "سر التطبيق يجب أن يكون سداسي عشري"
      : "App Secret must be hexadecimal",
    pleaseValidate: isAr
      ? "يرجى التحقق من المفاتيح قبل الحفظ"
      : "Please validate keys before saving",
    cannotSaveInvalid: isAr
      ? "لا يمكن حفظ مفاتيح غير صالحة"
      : "Cannot save invalid keys",
    keysSaved: isAr
      ? "تم حفظ مفاتيح WhatsApp بنجاح!"
      : "WhatsApp keys saved successfully!",
    keysRemoved: isAr
      ? "تم إزالة مفاتيح WhatsApp بنجاح"
      : "WhatsApp keys removed successfully",
    copySuccess: isAr ? "تم النسخ!" : "Copied!",
    subscribeToEvents: isAr
      ? "اشترك في الأحداث التالية:"
      : "Subscribe to these events:",
  };

  // Input values
  const [phoneNumberId, setPhoneNumberId] = useState("");
  const [accessToken, setAccessToken] = useState("");
  const [appSecret, setAppSecret] = useState("");
  const [displayNumber, setDisplayNumber] = useState("");

  // Visibility toggles
  const [showAccessToken, setShowAccessToken] = useState(false);
  const [showAppSecret, setShowAppSecret] = 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);
  const [copiedField, setCopiedField] = useState<string | null>(null);

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

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

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

        // If keys exist, populate phone number ID
        if (data.hasKeys && data.phoneNumberId) {
          setPhoneNumberId(data.phoneNumberId);
        }
      } 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);
    }
  }, []);

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

  const copyToClipboard = async (text: string, field: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedField(field);
      setTimeout(() => setCopiedField(null), 2000);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

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

    // Validation
    if (!phoneNumberId.trim() || !accessToken.trim() || !appSecret.trim()) {
      setError(t.keysRequired);
      return;
    }

    // Check key formats
    if (!/^\d+$/.test(phoneNumberId)) {
      setError(t.invalidPhoneNumberId);
      return;
    }

    if (!accessToken.startsWith("EAA")) {
      setError(t.invalidAccessToken);
      return;
    }

    if (!/^[a-f0-9]+$/i.test(appSecret)) {
      setError(t.invalidAppSecret);
      return;
    }

    try {
      setValidating(true);
      const response = await fetchWithCSRF(
        "/api/settings/whatsapp-keys/validate",
        {
          method: "POST",
          body: JSON.stringify({
            phoneNumberId: phoneNumberId.trim(),
            accessToken: accessToken.trim(),
          }),
        },
      );

      const data = await response.json();

      if (response.ok) {
        setValidationResult({
          valid: data.valid,
          displayNumber: data.displayNumber,
          businessName: data.businessName,
          message: data.valid ? t.keysValid : data.error || t.validationFailed,
        });
        setIsValidated(data.valid);
        if (data.valid && data.displayNumber) {
          setDisplayNumber(data.displayNumber);
        }
        if (!data.valid) {
          setError(data.error || t.validationFailed);
        }
      } else {
        setError(data.error || "Validation request failed");
        setValidationResult({
          valid: false,
          message: data.error || t.validationFailed,
        });
      }
    } catch (err) {
      console.error("Validation error:", err);
      setError(err instanceof Error ? err.message : "Failed to validate keys");
      setValidationResult({
        valid: false,
        message: "Network error during validation",
      });
    } finally {
      setValidating(false);
    }
  };

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

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

    try {
      setSaving(true);
      setError(null);
      const response = await fetchWithCSRF("/api/settings/whatsapp-keys", {
        method: "POST",
        body: JSON.stringify({
          phoneNumberId: phoneNumberId.trim(),
          accessToken: accessToken.trim(),
          appSecret: appSecret.trim(),
          displayNumber: displayNumber.trim() || undefined,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        alert(t.keysSaved);
        setAccessToken("");
        setAppSecret("");
        setValidationResult(null);
        setIsValidated(false);
        await fetchExistingKeys();
      } else {
        setError(data.error || "Failed to save keys");
      }
    } catch (err) {
      console.error("Save error:", err);
      setError(err instanceof Error ? 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 fetchWithCSRF("/api/settings/whatsapp-keys", {
        method: "DELETE",
      });

      if (response.ok) {
        alert(t.keysRemoved);
        setPhoneNumberId("");
        setAccessToken("");
        setAppSecret("");
        setDisplayNumber("");
        setValidationResult(null);
        setIsValidated(false);
        await fetchExistingKeys();
      } else {
        const data = await response.json();
        setError(data.error || "Failed to remove keys");
      }
    } catch (err) {
      console.error("Delete error:", err);
      setError(err instanceof Error ? 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.canManageWhatsApp) {
    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-green-50 border border-green-200 rounded-xl p-4">
        <div
          className={`flex items-start gap-3 ${isAr ? "flex-row-reverse" : ""}`}
        >
          <Shield className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
          <div>
            <h4 className="font-semibold text-green-900 mb-1">
              {isAr ? "تشفير آمن" : "Secure Encryption"}
            </h4>
            <p className="text-sm text-green-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" : ""}`}
          >
            <MessageCircle className="w-6 h-6 text-green-600" />
            <div>
              <h3 className="text-lg font-bold text-slate-900">
                {t.currentConfig}
              </h3>
              <div className="flex items-center gap-2">
                <span
                  className={`inline-flex px-2 py-0.5 text-xs font-medium rounded-full ${
                    existingKeys.webhookVerified
                      ? "bg-green-100 text-green-800"
                      : "bg-yellow-100 text-yellow-800"
                  }`}
                >
                  {existingKeys.webhookVerified
                    ? t.webhookVerified
                    : t.webhookPending}
                </span>
              </div>
            </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.phoneNumberId}
                </label>
                <code className="block text-sm bg-slate-100 px-3 py-2 rounded-lg border border-slate-200">
                  {existingKeys.phoneNumberId || "••••••••"}
                </code>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  {t.displayNumber}
                </label>
                <p className="text-base text-slate-900 px-3 py-2">
                  {existingKeys.displayNumber || "--"}
                </p>
              </div>
            </div>

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

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

            {/* Webhook Configuration */}
            {existingKeys.webhookUrl && existingKeys.verifyToken && (
              <div className="mt-6 pt-4 border-t border-slate-200">
                <h4 className="font-semibold text-slate-900 mb-3">
                  {t.webhookConfig}
                </h4>
                <div className="space-y-3 bg-slate-50 p-4 rounded-lg">
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {t.webhookUrl}
                    </label>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 text-sm bg-white px-3 py-2 rounded-lg border border-slate-200 break-all">
                        {existingKeys.webhookUrl}
                      </code>
                      <button
                        onClick={() =>
                          copyToClipboard(
                            existingKeys.webhookUrl!,
                            "webhookUrl",
                          )
                        }
                        className="p-2 text-slate-500 hover:text-slate-700"
                        title="Copy"
                      >
                        {copiedField === "webhookUrl" ? (
                          <Check className="w-4 h-4 text-green-600" />
                        ) : (
                          <Copy className="w-4 h-4" />
                        )}
                      </button>
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {t.verifyToken}
                    </label>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 text-sm bg-white px-3 py-2 rounded-lg border border-slate-200 font-mono">
                        {existingKeys.verifyToken}
                      </code>
                      <button
                        onClick={() =>
                          copyToClipboard(
                            existingKeys.verifyToken!,
                            "verifyToken",
                          )
                        }
                        className="p-2 text-slate-500 hover:text-slate-700"
                        title="Copy"
                      >
                        {copiedField === "verifyToken" ? (
                          <Check className="w-4 h-4 text-green-600" />
                        ) : (
                          <Copy className="w-4 h-4" />
                        )}
                      </button>
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                      {t.subscribeToEvents}
                    </label>
                    <ul className="text-sm text-slate-600 list-disc list-inside">
                      <li>messages</li>
                      <li>message_status (optional)</li>
                    </ul>
                  </div>
                </div>
              </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">
          {/* Phone Number ID */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.phoneNumberId} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={phoneNumberId}
              onChange={(e) => {
                setPhoneNumberId(e.target.value.replace(/\D/g, ""));
                setValidationResult(null);
                setIsValidated(false);
              }}
              placeholder="123456789012345"
              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.phoneNumberIdHint}</p>
          </div>

          {/* Access Token */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.accessToken} <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type={showAccessToken ? "text" : "password"}
                value={accessToken}
                onChange={(e) => {
                  setAccessToken(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="EAAxxxxxxxxxx..."
                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={() => setShowAccessToken(!showAccessToken)}
                className={`absolute ${isAr ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600`}
              >
                {showAccessToken ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
            <p className="text-xs text-slate-500 mt-1">{t.accessTokenHint}</p>
          </div>

          {/* App Secret */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.appSecret} <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type={showAppSecret ? "text" : "password"}
                value={appSecret}
                onChange={(e) => {
                  setAppSecret(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="abc123def456..."
                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={() => setShowAppSecret(!showAppSecret)}
                className={`absolute ${isAr ? "left-3" : "right-3"} top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600`}
              >
                {showAppSecret ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
            <p className="text-xs text-slate-500 mt-1">{t.appSecretHint}</p>
          </div>

          {/* Display Number (Optional) */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.displayNumber}{" "}
              <span className="text-slate-500">({t.optional})</span>
            </label>
            <input
              type="text"
              value={displayNumber}
              onChange={(e) => setDisplayNumber(e.target.value)}
              placeholder="+1 234 567 8900"
              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.displayNumberHint}</p>
          </div>

          {/* Validation Result */}
          {validationResult && (
            <div
              className={`p-4 rounded-xl border-2 ${
                validationResult.valid
                  ? "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 ? (
                  <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 ? "text-green-900" : "text-red-900"
                    }`}
                  >
                    {validationResult.valid ? t.keysValid : t.validationFailed}
                  </p>
                  <p
                    className={`text-sm mt-1 ${
                      validationResult.valid ? "text-green-800" : "text-red-800"
                    }`}
                  >
                    {validationResult.message}
                  </p>
                  {validationResult.valid && (
                    <div className="mt-2 text-sm text-green-800">
                      {validationResult.displayNumber && (
                        <p>
                          <strong>{t.displayNumber}:</strong>{" "}
                          {validationResult.displayNumber}
                        </p>
                      )}
                      {validationResult.businessName && (
                        <p>
                          <strong>{t.businessName}:</strong>{" "}
                          {validationResult.businessName}
                        </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 ||
                !phoneNumberId.trim() ||
                !accessToken.trim() ||
                !appSecret.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://developers.facebook.com/apps"
          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.openMetaConsole}
        </a>
      </div>
    </div>
  );
}
