'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import {
  Settings,
  ShoppingBag,
  MessageSquare,
  CreditCard,
  CheckCircle,
  AlertCircle,
  Share2,
  Lock,
  ArrowRight,
} from 'lucide-react';

interface Integration {
  id: string;
  integrationType: string;
  integrationName: string;
  status: string;
  lastConnectedAt: string | null;
  credentials: Record<string, any>;
}

export default function IntegrationsPage() {
  const { user } = useAuth();
  const isNotActivated = user && (user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED' || user.status === 'EXPIRED');

  const [integrations, setIntegrations] = useState<Integration[]>([]);
  const [loading, setLoading] = useState(true);
  const [testing, setTesting] = useState<Record<string, boolean>>({});
  const [testResult, setTestResult] = useState<Record<string, { success: boolean; message: string }>>({});
  const [saving, setSaving] = useState<Record<string, boolean>>({});

  // WooCommerce State
  const [wcUrl, setWcUrl] = useState('');
  const [wcKey, setWcKey] = useState('');
  const [wcSecret, setWcSecret] = useState('');
  const [wcSandbox, setWcSandbox] = useState(true);
  const [settingUpWebhooks, setSettingUpWebhooks] = useState(false);

  // WhatsApp State
  const [waPhoneId, setWaPhoneId] = useState('');
  const [waToken, setWaToken] = useState('');

  // PesePay State
  const [pesepayMerchantKey, setPesepayMerchantKey] = useState('');
  const [pesepayEncryptionKey, setPesepayEncryptionKey] = useState('');

  // Meta / WhatsApp Native Catalog State
  const [metaCatalogId, setMetaCatalogId] = useState('');
  const [metaToken, setMetaToken] = useState('');

  useEffect(() => {
    if (!isNotActivated) {
      fetchIntegrations();
    } else {
      setLoading(false);
    }
  }, [isNotActivated]);

  async function fetchIntegrations() {
    try {
      const data = await apiRequest('api/integrations');
      setIntegrations(data);
      
      // Load pre-existing values if configured
      const wc = data.find((i: any) => i.integrationType === 'woocommerce');
      if (wc) {
        setWcUrl(wc.credentials.storeUrl || '');
        setWcKey(wc.credentials.consumerKey || '');
        setWcSecret(wc.credentials.consumerSecret || '');
        setWcSandbox(wc.credentials.isSandbox ?? true);
      }

      const wa = data.find((i: any) => i.integrationType === 'whatsapp');
      if (wa) {
        setWaPhoneId(wa.credentials.phoneNumberId || '');
        setWaToken(wa.credentials.accessToken || '');
      }

      const metaCat = data.find((i: any) => i.integrationType === 'meta_catalog' || i.integrationType === 'whatsapp_catalog' || i.integrationType === 'meta');
      if (metaCat) {
        setMetaCatalogId(metaCat.credentials.catalogId || metaCat.credentials.metaCatalogId || '');
        setMetaToken(metaCat.credentials.accessToken || metaCat.credentials.metaAccessToken || '');
      }

      const pesepay = data.find((i: any) => i.integrationType === 'pesepay');
      if (pesepay) {
        setPesepayMerchantKey(pesepay.credentials.pesepayMerchantKey || '');
        setPesepayEncryptionKey(pesepay.credentials.pesepayEncryptionKey || '');
      }
    } catch (err) {
      console.error('Failed to load integrations:', err);
    } finally {
      setLoading(false);
    }
  }

  const handleTestConnection = async (type: string, credentials: Record<string, any>) => {
    setTesting((prev) => ({ ...prev, [type]: true }));
    setTestResult((prev) => {
      const copy = { ...prev };
      delete copy[type];
      return copy;
    });

    try {
      const res = await apiRequest('api/integrations/test', 'POST', {
        integrationType: type,
        credentials,
      });
      setTestResult((prev) => ({
        ...prev,
        [type]: { success: res.success, message: res.message },
      }));
    } catch (err: any) {
      setTestResult((prev) => ({
        ...prev,
        [type]: { success: false, message: err.message || 'Connection failed' },
      }));
    } finally {
      setTesting((prev) => ({ ...prev, [type]: false }));
    }
  };

  const handleSaveIntegration = async (type: string, name: string, credentials: Record<string, any>) => {
    setSaving((prev) => ({ ...prev, [type]: true }));
    try {
      await apiRequest('api/integrations/connect', 'POST', {
        integrationType: type,
        integrationName: name,
        credentials,
      });
      await fetchIntegrations();
      alert(`${name} saved and activated!`);
    } catch (err: any) {
      alert(`Failed to save: ${err.message}`);
    } finally {
      setSaving((prev) => ({ ...prev, [type]: false }));
    }
  };

  const handleSetupWebhooks = async () => {
    const defaultUrl = window.location.origin.includes('localhost')
      ? ''
      : window.location.origin;
      
    const publicUrl = prompt(
      "Enter your cloudflared public tunnel URL (e.g., https://your-subdomain.trycloudflare.com):\n\nYou can find this domain in the terminal where your cloudflared tunnel is running.",
      defaultUrl
    );
    
    if (publicUrl === null) return; // user cancelled
    if (!publicUrl.trim()) {
      alert("Public tunnel URL is required to receive webhooks from WooCommerce.");
      return;
    }

    setSettingUpWebhooks(true);
    try {
      const res = await apiRequest('api/integrations/woocommerce/setup-webhooks', 'POST', {
        publicUrl: publicUrl.trim()
      });
      alert(res.message);
    } catch (err: any) {
      alert(`Webhook configuration failed: ${err.message}`);
    } finally {
      setSettingUpWebhooks(false);
    }
  };

  const activeWc = integrations.find((i) => i.integrationType === 'woocommerce' && i.status === 'ACTIVE');
  const hasWhatsApp = integrations.some((i) => i.integrationType === 'whatsapp' && i.status === 'ACTIVE');
  const hasMetaCatalog = integrations.some((i) => (i.integrationType === 'meta_catalog' || i.integrationType === 'whatsapp_catalog' || i.integrationType === 'meta') && i.status === 'ACTIVE');

  if (isNotActivated) {
    return (
      <div className="max-w-3xl mx-auto glass-panel rounded-3xl p-8 lg:p-12 text-center space-y-6 my-12 font-sans shadow-2xl border border-amber-500/30">
        <div className="flex justify-center mx-auto py-2">
          <Image
            src="/assets/icons8-locked.svg"
            alt="Locked"
            width={64}
            height={64}
            className="w-16 h-16 object-contain mx-auto"
          />
        </div>
        <div className="space-y-2">
          <h2 className="text-2xl font-black text-white font-sans">Integrations Locked</h2>
          <p className="text-xs text-amber-400 font-bold uppercase tracking-wider">Account Not Activated</p>
        </div>
        <p className="text-xs text-gray-300 max-w-md mx-auto leading-relaxed">
          You must activate your account by choosing a <strong>14-day Free Trial</strong> or completing a <strong>Subscription Payment</strong> before accessing store integrations.
        </p>
        <div className="pt-2">
          <Link
            href="/dashboard/billing"
            className="inline-flex items-center justify-center gap-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold px-8 py-4 rounded-xl text-xs uppercase tracking-wider transition-all shadow-md active:scale-[0.98]"
          >
            <span>Activate Account on Billing Page</span>
            <ArrowRight className="w-4 h-4" />
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-3xl font-extrabold tracking-tight text-white Outfit">
          Integrations & Credentials
        </h1>
        <p className="text-sm text-gray-400 mt-1">
          Connect your store backend, messaging bot, and payment gateways safely
        </p>
      </div>

      {loading ? (
        <div className="flex h-64 items-center justify-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
        </div>
      ) : (
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
          {/* WooCommerce Card */}
          <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-xl bg-[#EFEAE2]/10 dark:bg-transparent flex items-center justify-center border border-[#EFEAE2]/20 dark:border-[#EFEAE2]/15 overflow-hidden">
                <img src="/assets/woo.png" alt="WooCommerce" className="h-7 w-7 object-contain" />
              </div>
              <div>
                <h3 className="font-bold text-white text-lg font-sans">WooCommerce Connector</h3>
                <p className="text-xs text-gray-500 mt-0.5">Active connector to sync products and push orders</p>
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between bg-white/3 p-3 rounded-lg border border-white/5">
                <span className="text-xs text-gray-400">Sandbox Mode (Enable to test locally without WooCommerce keys)</span>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={wcSandbox}
                    onChange={(e) => setWcSandbox(e.target.checked)}
                    className="sr-only peer"
                  />
                  <div className="w-9 h-5 bg-gray-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-emerald-500"></div>
                </label>
              </div>

              {!wcSandbox && (
                <>
                  <div className="grid grid-cols-1 gap-4">
                    <div>
                      <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Store Domain URL</label>
                      <input
                        type="url"
                        value={wcUrl}
                        onChange={(e) => setWcUrl(e.target.value)}
                        className="w-full glass-input px-4 py-2 text-sm"
                        placeholder="https://yourstore.com"
                      />
                    </div>
                    <div>
                      <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Consumer Key (CK)</label>
                      <input
                        type="text"
                        value={wcKey}
                        onChange={(e) => setWcKey(e.target.value)}
                        className="w-full glass-input px-4 py-2 text-sm"
                        placeholder="ck_xxxxxxxxxxxx"
                      />
                    </div>
                    <div>
                      <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Consumer Secret (CS)</label>
                      <input
                        type="password"
                        value={wcSecret}
                        onChange={(e) => setWcSecret(e.target.value)}
                        className="w-full glass-input px-4 py-2 text-sm"
                        placeholder="cs_xxxxxxxxxxxx"
                      />
                    </div>
                  </div>
                </>
              )}
            </div>

            {testResult['woocommerce'] && (
              <div className={`p-3 rounded-lg text-xs flex gap-2 items-start ${
                testResult['woocommerce'].success
                  ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400'
                  : 'bg-red-500/10 border border-red-500/20 text-red-400'
              }`}>
                {testResult['woocommerce'].success ? <CheckCircle className="h-4 w-4 shrink-0 mt-0.5" /> : <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />}
                <span>{testResult['woocommerce'].message}</span>
              </div>
            )}

            <div className="flex gap-4 pt-2">
              <button
                type="button"
                onClick={() => handleTestConnection('woocommerce', { storeUrl: wcUrl, consumerKey: wcKey, consumerSecret: wcSecret, isSandbox: wcSandbox })}
                disabled={testing['woocommerce']}
                className="flex-1 glass-input border-[#EFEAE2]/20 text-[#EFEAE2] hover:bg-[#EFEAE2]/5 font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer"
              >
                {testing['woocommerce'] ? 'Testing Connection...' : 'Test Connection'}
              </button>
              <button
                type="button"
                onClick={() => handleSaveIntegration('woocommerce', wcSandbox ? 'WooCommerce Sandbox' : 'WooCommerce Production', { storeUrl: wcUrl, consumerKey: wcKey, consumerSecret: wcSecret, isSandbox: wcSandbox })}
                disabled={saving['woocommerce']}
                className="flex-1 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10"
              >
                {saving['woocommerce'] ? 'Saving...' : 'Save Integration'}
              </button>
            </div>

            {activeWc && (
              <div className="pt-4 border-t border-white/5 space-y-3">
                <div className="flex items-center justify-between bg-white/3 p-3 rounded-lg border border-white/5">
                  <div className="space-y-0.5">
                    <h4 className="text-xs font-semibold text-white font-sans">Realtime Webhooks</h4>
                    <p className="text-[10px] text-gray-400">Subscribe WooCommerce to order updates automatically</p>
                  </div>
                  <button
                    type="button"
                    onClick={handleSetupWebhooks}
                    disabled={settingUpWebhooks}
                    className="px-3 py-2 bg-emerald-500/20 hover:bg-emerald-500/30 border border-emerald-500/30 text-emerald-300 font-semibold rounded-lg text-[10px] transition-all cursor-pointer disabled:opacity-50"
                  >
                    {settingUpWebhooks ? 'Setting up...' : 'Setup Webhooks'}
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Meta / WhatsApp Native Catalog */}
          <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden">
            <div className="flex items-center justify-between gap-4 flex-wrap">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-[#EFEAE2]/10 dark:bg-transparent flex items-center justify-center border border-[#EFEAE2]/20 dark:border-[#EFEAE2]/15 overflow-hidden">
                  <img src="/assets/icons8-whatsapp.svg" alt="WhatsApp" className="h-7 w-7 object-contain" />
                </div>
                <div>
                  <h3 className="font-bold text-white text-lg font-sans">Meta / WhatsApp Native Catalog</h3>
                  <p className="text-xs text-gray-500 mt-0.5">Sync products and inventory natively to WhatsApp Business / Facebook Shop</p>
                </div>
              </div>

              <div className="flex items-center gap-2 bg-white/3 px-3 py-1.5 rounded-full border border-white/5 text-xs text-gray-300">
                <span>
                  Catalog Status: <strong className={hasMetaCatalog ? 'text-emerald-400' : 'text-amber-400'}>
                    {hasMetaCatalog ? 'Active (Synced)' : 'Not Connected'}
                  </strong>
                </span>
              </div>
            </div>

            <div className="space-y-4">
              <div className="bg-white/3 p-3 rounded-lg border border-white/5 text-xs text-emerald-400 font-medium">
                Connect your Meta Commerce Manager Catalog ID so products auto-sync when added or updated.
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Meta Catalog ID</label>
                  <input
                    type="text"
                    value={metaCatalogId}
                    onChange={(e) => setMetaCatalogId(e.target.value)}
                    className="w-full glass-input px-4 py-2 text-sm font-mono"
                    placeholder="e.g. 10459384958392"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">System User Access Token</label>
                  <input
                    type="password"
                    value={metaToken}
                    onChange={(e) => setMetaToken(e.target.value)}
                    className="w-full glass-input px-4 py-2 text-sm font-mono"
                    placeholder="EAAWxxxxxxxxxxxx..."
                  />
                </div>
              </div>
            </div>

            {testResult['meta_catalog'] && (
              <div className={`p-3 rounded-lg text-xs flex gap-2 items-start ${
                testResult['meta_catalog'].success
                  ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400'
                  : 'bg-red-500/10 border border-red-500/20 text-red-400'
              }`}>
                {testResult['meta_catalog'].success ? <CheckCircle className="h-4 w-4 shrink-0 mt-0.5" /> : <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />}
                <span>{testResult['meta_catalog'].message}</span>
              </div>
            )}

            <div className="flex gap-4 pt-2">
              <button
                type="button"
                onClick={() => handleTestConnection('meta_catalog', { catalogId: metaCatalogId, accessToken: metaToken, isSandbox: !metaCatalogId })}
                disabled={testing['meta_catalog']}
                className="flex-1 glass-input border-[#EFEAE2]/20 text-[#EFEAE2] hover:bg-[#EFEAE2]/5 font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer"
              >
                {testing['meta_catalog'] ? 'Testing Connection...' : 'Test Catalog Connection'}
              </button>
              <button
                type="button"
                onClick={() => handleSaveIntegration('meta_catalog', 'Meta / WhatsApp Native Catalog', { catalogId: metaCatalogId, accessToken: metaToken, isSandbox: !metaCatalogId })}
                disabled={saving['meta_catalog']}
                className="flex-1 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10"
              >
                {saving['meta_catalog'] ? 'Saving...' : 'Save Catalog Configuration'}
              </button>
            </div>
          </div>

          {/* PesePay Zimbabwean Gateway */}
          <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-xl bg-[#EFEAE2]/10 dark:bg-transparent flex items-center justify-center border border-[#EFEAE2]/20 dark:border-[#EFEAE2]/15 overflow-hidden">
                <img src="/assets/pesepay_logo.jfif" alt="PesePay" className="h-7 w-7 object-contain" />
              </div>
              <div>
                <h3 className="font-bold text-white text-lg font-sans">PesePay Payment Gateway</h3>
                <p className="text-xs text-gray-500 mt-0.5">Zimbabwean localized payment connector (EcoCash/OneMoney/Visa/Mastercard)</p>
              </div>
            </div>

            <div className="space-y-4">
              <div className="bg-white/3 p-3 rounded-lg border border-white/5 text-xs text-emerald-400 font-medium">
                Leave empty or use sandbox values to test via our mock sandbox payment page.
              </div>
              <div className="grid grid-cols-1 gap-4">
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">PesePay Merchant Key</label>
                  <input
                    type="text"
                    value={pesepayMerchantKey}
                    onChange={(e) => setPesepayMerchantKey(e.target.value)}
                    className="w-full glass-input px-4 py-2 text-sm"
                    placeholder="Enter PesePay Merchant Key"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">PesePay Encryption Key</label>
                  <input
                    type="password"
                    value={pesepayEncryptionKey}
                    onChange={(e) => setPesepayEncryptionKey(e.target.value)}
                    className="w-full glass-input px-4 py-2 text-sm"
                    placeholder="Enter PesePay Encryption Key"
                  />
                </div>
              </div>
            </div>

            {testResult['pesepay'] && (
              <div className={`p-3 rounded-lg text-xs flex gap-2 items-start ${
                testResult['pesepay'].success
                  ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400'
                  : 'bg-red-500/10 border border-red-500/20 text-red-400'
              }`}>
                {testResult['pesepay'].success ? <CheckCircle className="h-4 w-4 shrink-0 mt-0.5" /> : <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />}
                <span>{testResult['pesepay'].message}</span>
              </div>
            )}

            <div className="flex gap-4 pt-2">
              <button
                type="button"
                onClick={() => handleTestConnection('pesepay', { pesepayMerchantKey, pesepayEncryptionKey, isSandbox: !pesepayMerchantKey })}
                disabled={testing['pesepay']}
                className="flex-1 glass-input border-[#EFEAE2]/20 text-[#EFEAE2] hover:bg-[#EFEAE2]/5 font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer"
              >
                {testing['pesepay'] ? 'Testing Connection...' : 'Test Connection'}
              </button>
              <button
                type="button"
                onClick={() => handleSaveIntegration('pesepay', 'PesePay Integration', { pesepayMerchantKey, pesepayEncryptionKey, isSandbox: !pesepayMerchantKey })}
                disabled={saving['pesepay']}
                className="flex-1 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10"
              >
                {saving['pesepay'] ? 'Saving...' : 'Save Integration'}
              </button>
            </div>
          </div>

          {/* WhatsApp API Credentials */}
          <div className="glass-panel rounded-2xl p-6 space-y-6 relative overflow-hidden xl:col-span-2">
            <div className="flex items-center justify-between gap-4 flex-wrap">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-xl bg-[#EFEAE2]/10 dark:bg-transparent flex items-center justify-center border border-[#EFEAE2]/20 dark:border-[#EFEAE2]/15 overflow-hidden">
                  <img src="/assets/icons8-whatsapp.svg" alt="WhatsApp" className="h-7 w-7 object-contain" />
                </div>
                <div>
                  <h3 className="font-bold text-white text-lg font-sans">Meta WhatsApp Cloud API (Optional)</h3>
                  <p className="text-xs text-gray-500 mt-0.5">Deploy the bot to actual client numbers. Otherwise, simulator will be active</p>
                </div>
              </div>

              <div className="flex items-center gap-2 bg-white/3 px-3 py-1.5 rounded-full border border-white/5 text-xs text-gray-300">
                <span>
                  WhatsApp Status: <strong className={hasWhatsApp ? 'text-emerald-400' : 'text-red-400'}>
                    {hasWhatsApp ? 'Connected (Direct)' : 'Not Configured'}
                  </strong>
                </span>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Phone Number ID</label>
                  <input
                    type="text"
                    value={waPhoneId}
                    onChange={(e) => setWaPhoneId(e.target.value)}
                    className="w-full glass-input px-4 py-2 text-sm"
                    placeholder="WABA Phone Number ID"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-semibold uppercase tracking-wider text-gray-500 mb-2">Graph Access Token (Permanent)</label>
                  <input
                    type="password"
                    value={waToken}
                    onChange={(e) => setWaToken(e.target.value)}
                    className="w-full glass-input px-4 py-2 text-sm"
                    placeholder="EAAWxxxxxxxxxxxx"
                  />
                </div>
              </div>

              <div className="bg-white/3 p-4 rounded-xl border border-white/5 space-y-3 flex flex-col justify-center">
                <h4 className="font-semibold text-xs text-white">Your Webhook Web Address</h4>
                <p className="text-xs text-gray-400 leading-relaxed">
                  Provide this webhook URL in your Meta Facebook Developer Console under the WhatsApp product configurations:
                </p>
                <code className="bg-black/40 text-emerald-400 p-2 rounded text-xs select-all break-all border border-white/5 font-mono">
                  {typeof window !== 'undefined' ? `${window.location.origin.replace('3000', '3001')}/webhooks/whatsapp` : 'http://localhost:3001/webhooks/whatsapp'}
                </code>
                <div className="flex gap-2 items-center text-xs text-gray-500">
                  <span>Verification Token:</span>
                  <code className="text-white font-mono bg-white/5 px-2 py-0.5 rounded">whatsapp-verify-token</code>
                </div>
              </div>
            </div>

            {testResult['whatsapp'] && (
              <div className={`p-3 rounded-lg text-xs flex gap-2 items-start ${
                testResult['whatsapp'].success
                  ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400'
                  : 'bg-red-500/10 border border-red-500/20 text-red-400'
              }`}>
                {testResult['whatsapp'].success ? <CheckCircle className="h-4 w-4 shrink-0 mt-0.5" /> : <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />}
                <span>{testResult['whatsapp'].message}</span>
              </div>
            )}

            <div className="flex gap-4 pt-2">
              <button
                type="button"
                onClick={() => handleTestConnection('whatsapp', { phoneNumberId: waPhoneId, accessToken: waToken })}
                disabled={testing['whatsapp']}
                className="flex-1 glass-input border-[#EFEAE2]/20 text-[#EFEAE2] hover:bg-[#EFEAE2]/5 font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer"
              >
                {testing['whatsapp'] ? 'Testing Connection...' : 'Test Connection'}
              </button>
              <button
                type="button"
                onClick={() => handleSaveIntegration('whatsapp', 'WhatsApp Cloud API', { phoneNumberId: waPhoneId, accessToken: waToken })}
                disabled={saving['whatsapp']}
                className="flex-1 bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 rounded-lg text-xs transition-all cursor-pointer shadow-md shadow-emerald-500/10"
              >
                {saving['whatsapp'] ? 'Saving...' : 'Save Configuration'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
