'use client';

import React, { useState, useEffect } from 'react';
import { apiRequest } from '@/lib/api';
import { toast } from '@/context/ToastContext';
import dynamic from 'next/dynamic';

const RichTextEditor = dynamic(() => import('@/components/admin/RichTextEditor'), {
  ssr: false,
  loading: () => <div className="w-full h-[300px] bg-gray-50 border border-gray-200 rounded-2xl flex items-center justify-center text-sm text-gray-500 font-medium">Loading editor...</div>
});

import {
  Clock,
  Save,
  CheckCircle2,
  Sliders,
  ShieldCheck,
  FileText,
  CreditCard,
  Building2,
  Eye,
  EyeOff,
  Copy,
  Check,
  Lock,
  Globe,
  Sparkles,
  KeyRound,
} from 'lucide-react';

export default function AdminSettingsPage() {
  const [activeTab, setActiveTab] = useState<'system' | 'privacy' | 'terms'>('system');

  // System Settings state
  const [defaultValidityMonths, setDefaultValidityMonths] = useState<number>(4);
  const [defaultCurrency, setDefaultCurrency] = useState('EUR');

  // Stripe Settings State
  const [stripeEnabled, setStripeEnabled] = useState(true);
  const [stripeMode, setStripeMode] = useState<'test' | 'live'>('test');
  // Stripe Test Keys
  const [stripeTestPub, setStripeTestPub] = useState('');
  const [stripeTestSec, setStripeTestSec] = useState('');
  // Stripe Live Keys
  const [stripeLivePub, setStripeLivePub] = useState('');
  const [stripeLiveSec, setStripeLiveSec] = useState('');

  // PayPal Settings State
  const [paypalEnabled, setPaypalEnabled] = useState(true);
  const [paypalMode, setPaypalMode] = useState<'test' | 'live'>('test');
  // PayPal Test Credentials
  const [paypalTestClientId, setPaypalTestClientId] = useState('');
  const [paypalTestClientSecret, setPaypalTestClientSecret] = useState('');
  // PayPal Live Credentials
  const [paypalLiveClientId, setPaypalLiveClientId] = useState('');
  const [paypalLiveClientSecret, setPaypalLiveClientSecret] = useState('');

  // Bank Transfer Settings State
  const [bankEnabled, setBankEnabled] = useState(true);
  const [bankName, setBankName] = useState('');
  const [accountHolder, setAccountHolder] = useState('');
  const [iban, setIban] = useState('');
  const [bicSwift, setBicSwift] = useState('');
  const [paymentInstructions, setPaymentInstructions] = useState(
    'Please transfer the course fee to our bank account and upload your receipt screenshot in checkout.'
  );

  // Toggle Secret Key Visibility
  const [showStripeTestSec, setShowStripeTestSec] = useState(false);
  const [showStripeLiveSec, setShowStripeLiveSec] = useState(false);
  const [showPaypalTestSecret, setShowPaypalTestSecret] = useState(false);
  const [showPaypalLiveSecret, setShowPaypalLiveSecret] = useState(false);

  // Copy Feedback State per Field Key
  const [copiedField, setCopiedField] = useState<string | null>(null);

  // Legal Content state
  const [privacyPolicy, setPrivacyPolicy] = useState(
    '# Privacy Policy\n\nApkaGermanSchool protects your personal data in accordance with strict privacy regulations.'
  );
  const [termsAndConditions, setTermsAndConditions] = useState(
    '# Terms & Conditions\n\nAll course content and educational material are copyrighted by ApkaGermanSchool.'
  );

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [savedSuccess, setSavedSuccess] = useState(false);

  const copyToClipboard = (text: string, fieldId: string, label: string) => {
    if (!text || text.trim() === '') {
      toast.error(`No ${label} to copy!`);
      return;
    }
    navigator.clipboard.writeText(text);
    setCopiedField(fieldId);
    toast.success(`${label} copied to clipboard!`);
    setTimeout(() => {
      setCopiedField((prev) => (prev === fieldId ? null : prev));
    }, 2000);
  };

  const fetchSettings = async () => {
    setLoading(true);
    const res = await apiRequest('/settings');
    if (res.success && res.settings) {
      const s = res.settings;

      if (s.defaultCourseExpiryMonths || s.defaultValidityMonths) {
        setDefaultValidityMonths(s.defaultCourseExpiryMonths || s.defaultValidityMonths);
      }
      if (s.defaultCurrency) setDefaultCurrency(s.defaultCurrency);

      // Populate Stripe Settings
      if (s.stripe) {
        setStripeEnabled(s.stripe.isEnabled ?? true);
        setStripeMode(s.stripe.mode || 'test');
        setStripeTestPub(s.stripe.testPublishableKey || s.stripe.publishableKey || '');
        setStripeTestSec(s.stripe.testSecretKey || s.stripe.secretKey || '');
        setStripeLivePub(s.stripe.livePublishableKey || '');
        setStripeLiveSec(s.stripe.liveSecretKey || '');
      }

      // Populate PayPal Settings
      if (s.paypal) {
        setPaypalEnabled(s.paypal.isEnabled ?? true);
        setPaypalMode(s.paypal.mode === 'sandbox' ? 'test' : (s.paypal.mode || 'test'));
        setPaypalTestClientId(s.paypal.testClientId || s.paypal.clientId || '');
        setPaypalTestClientSecret(s.paypal.testClientSecret || s.paypal.clientSecret || '');
        setPaypalLiveClientId(s.paypal.liveClientId || '');
        setPaypalLiveClientSecret(s.paypal.liveClientSecret || '');
      }

      // Populate Bank Transfer Settings
      if (s.bankTransfer) {
        setBankEnabled(s.bankTransfer.isEnabled ?? true);
        setBankName(s.bankTransfer.bankName || '');
        setAccountHolder(s.bankTransfer.accountHolder || '');
        setIban(s.bankTransfer.iban || '');
        setBicSwift(s.bankTransfer.bicSwift || '');
        if (s.bankTransfer.paymentInstructions) {
          setPaymentInstructions(s.bankTransfer.paymentInstructions);
        }
      }

      if (s.legalPages) {
        if (s.legalPages.privacyPolicy) setPrivacyPolicy(s.legalPages.privacyPolicy);
        if (s.legalPages.termsAndConditions) setTermsAndConditions(s.legalPages.termsAndConditions);
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchSettings();
  }, []);

  const handleSaveSettings = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setSavedSuccess(false);

    const payload = {
      defaultCourseExpiryMonths: Number(defaultValidityMonths),
      defaultValidityMonths: Number(defaultValidityMonths),
      defaultCurrency,
      stripe: {
        mode: stripeMode,
        isEnabled: stripeEnabled,
        testPublishableKey: stripeTestPub,
        testSecretKey: stripeTestSec,
        livePublishableKey: stripeLivePub,
        liveSecretKey: stripeLiveSec,
      },
      paypal: {
        mode: paypalMode,
        isEnabled: paypalEnabled,
        testClientId: paypalTestClientId,
        testClientSecret: paypalTestClientSecret,
        liveClientId: paypalLiveClientId,
        liveClientSecret: paypalLiveClientSecret,
      },
      bankTransfer: {
        isEnabled: bankEnabled,
        bankName,
        accountHolder,
        iban,
        bicSwift,
        paymentInstructions,
      },
      legalPages: {
        privacyPolicy,
        termsAndConditions,
      },
    };

    const res = await apiRequest('/settings', {
      method: 'PUT',
      body: JSON.stringify(payload),
    });

    setSaving(false);

    if (res.success) {
      setSavedSuccess(true);
      toast.success('Settings updated successfully!');
      setTimeout(() => setSavedSuccess(false), 4000);
      fetchSettings();
    } else {
      toast.error(res.error || 'Failed to save settings');
    }
  };

  return (
    <div className="space-y-8 max-w-7xl mx-auto">
      {/* Header */}
      <div>
        {/* <div className="inline-flex items-center gap-2 rounded-full bg-amber-50 px-3 py-1 text-xs font-bold text-amber-700 border border-amber-200/60 mb-2">
          <Sparkles className="h-3.5 w-3.5 text-amber-500" />
          <span>Platform Control Hub</span>
        </div> */}
        <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight">Platform & Payment Settings</h1>
        <p className="text-sm text-gray-500 mt-1 max-w-3xl">
          Configure secure payment gateways, test/live credentials, direct bank transfer details, and student legal agreements.
        </p>
      </div>

      {/* Navigation Tabs */}
      <div className="flex border-b border-gray-200/80 gap-2 sm:gap-6 text-sm font-bold">
        <button
          type="button"
          onClick={() => setActiveTab('system')}
          className={`pb-3.5 border-b-2 flex items-center gap-2.5 transition ${activeTab === 'system'
            ? 'border-[#FECE00] text-gray-900 font-extrabold'
            : 'border-transparent text-gray-500 hover:text-gray-800'
            }`}
        >
          <Sliders className={`w-4 h-4 ${activeTab === 'system' ? 'text-[#D8A404]' : 'text-gray-400'}`} />
          <span>Payment Gateways</span>
        </button>

        <button
          type="button"
          onClick={() => setActiveTab('privacy')}
          className={`pb-3.5 border-b-2 flex items-center gap-2.5 transition ${activeTab === 'privacy'
            ? 'border-[#FECE00] text-gray-900 font-extrabold'
            : 'border-transparent text-gray-500 hover:text-gray-800'
            }`}
        >
          <ShieldCheck className={`w-4 h-4 ${activeTab === 'privacy' ? 'text-emerald-600' : 'text-gray-400'}`} />
          <span>Privacy Policy</span>
        </button>

        <button
          type="button"
          onClick={() => setActiveTab('terms')}
          className={`pb-3.5 border-b-2 flex items-center gap-2.5 transition ${activeTab === 'terms'
            ? 'border-[#FECE00] text-gray-900 font-extrabold'
            : 'border-transparent text-gray-500 hover:text-gray-800'
            }`}
        >
          <FileText className={`w-4 h-4 ${activeTab === 'terms' ? 'text-blue-600' : 'text-gray-400'}`} />
          <span>Terms & Conditions</span>
        </button>
      </div>

      {savedSuccess && (
        <div className="p-4 rounded-2xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-xs font-bold flex items-center gap-2.5 shadow-xs">
          <CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0" />
          <span>Platform settings saved successfully! Changes are updated immediately across the application.</span>
        </div>
      )}

      {loading ? (
        <div className="bg-white rounded-3xl border border-gray-200/80 p-16 text-center text-sm font-semibold text-gray-500 shadow-xs">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-gray-200 border-t-[#FECE00] mb-4" />
          <p>Loading platform settings & credentials...</p>
        </div>
      ) : (
        <form onSubmit={handleSaveSettings} className="space-y-8">
          {/* TAB 1: Payment Gateways */}
          {activeTab === 'system' && (
            <div className="space-y-8">
              {/* STRIPE PAYMENT GATEWAY CARD */}
              <div className="bg-white rounded-3xl border border-gray-200/80 shadow-xs overflow-hidden transition-all duration-200 hover:shadow-md">
                <div className="p-6 border-b border-gray-100 bg-gradient-to-r from-purple-50/40 via-white to-transparent flex flex-wrap items-center justify-between gap-4">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-purple-600/10 text-purple-700 border border-purple-200/60 flex items-center justify-center font-bold shadow-xs">
                      <CreditCard className="w-6 h-6" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2.5">
                        <h2 className="text-lg font-black text-gray-900 tracking-tight">Stripe Payments</h2>
                        <span
                          className={`inline-flex items-center gap-1.5 px-3 py-0.5 rounded-full text-xs font-bold tracking-wide transition-colors ${stripeMode === 'live'
                            ? 'bg-emerald-50 text-emerald-700 border border-emerald-200/60'
                            : 'bg-amber-50 text-amber-700 border border-amber-200/60'
                            }`}
                        >
                          <span
                            className={`w-2 h-2 rounded-full ${stripeMode === 'live' ? 'bg-emerald-500' : 'bg-amber-500'}`}
                          />
                          {stripeMode === 'live' ? 'Live Mode' : 'Test Mode'}
                        </span>
                      </div>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Accept credit cards, debit cards, and Apple Pay globally via Stripe.
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => setStripeEnabled(!stripeEnabled)}
                      className={`relative inline-flex h-7 w-12 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${stripeEnabled ? 'bg-emerald-500' : 'bg-gray-300'
                        }`}
                      role="switch"
                      aria-checked={stripeEnabled}
                    >
                      <span
                        className={`pointer-events-none inline-block h-6 w-6 transform rounded-full bg-white shadow-md ring-0 transition duration-200 ease-in-out ${stripeEnabled ? 'translate-x-5' : 'translate-x-0'
                          }`}
                      />
                    </button>
                    <span className="text-xs font-extrabold text-gray-700">
                      {stripeEnabled ? 'Enabled' : 'Disabled'}
                    </span>
                  </div>
                </div>

                <div className="p-6 space-y-6">
                  {/* Environment Switcher */}
                  <div>
                    <label className="block text-xs font-extrabold uppercase tracking-wider text-gray-500 mb-2">
                      Active Environment Mode
                    </label>
                    <div className="grid grid-cols-2 gap-3 max-w-md p-1 bg-gray-100/90 rounded-2xl border border-gray-200/70">
                      <button
                        type="button"
                        onClick={() => setStripeMode('test')}
                        className={`py-2.5 px-4 rounded-xl text-xs font-bold transition flex items-center justify-center gap-2 ${stripeMode === 'test'
                          ? 'bg-white text-gray-900 shadow-sm font-extrabold border border-gray-200'
                          : 'text-gray-500 hover:text-gray-800'
                          }`}
                      >
                        <span className="w-2 h-2 rounded-full bg-amber-500" />
                        <span>Test Mode</span>
                      </button>
                      <button
                        type="button"
                        onClick={() => setStripeMode('live')}
                        className={`py-2.5 px-4 rounded-xl text-xs font-bold transition flex items-center justify-center gap-2 ${stripeMode === 'live'
                          ? 'bg-white text-gray-900 shadow-sm font-extrabold border border-gray-200'
                          : 'text-gray-500 hover:text-gray-800'
                          }`}
                      >
                        <span className="w-2 h-2 rounded-full bg-emerald-500" />
                        <span>Live Mode</span>
                      </button>
                    </div>
                  </div>

                  {/* TEST MODE SECTION */}
                  {stripeMode === 'test' && (
                    <div className="p-6 rounded-2xl bg-gray-50/80 border border-gray-200/60 space-y-4">
                      <div className="flex items-center gap-2 text-amber-900 text-xs font-bold">
                        <KeyRound className="w-4 h-4 text-amber-600" />
                        <span>Stripe Test Credentials</span>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        {/* Test Publishable Key */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Test Publishable Key
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type="text"
                              value={stripeTestPub}
                              onChange={(e) => setStripeTestPub(e.target.value)}
                              placeholder="pk_test_..."
                              className="w-full px-3.5 py-2.5 pr-11 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <button
                              type="button"
                              onClick={() => copyToClipboard(stripeTestPub, 'stripeTestPub', 'Test Publishable Key')}
                              title="Copy key"
                              className="absolute right-2 p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                            >
                              {copiedField === 'stripeTestPub' ? (
                                <Check className="w-4 h-4 text-emerald-600" />
                              ) : (
                                <Copy className="w-4 h-4" />
                              )}
                            </button>
                          </div>
                        </div>

                        {/* Test Secret Key */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Test Secret Key
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type={showStripeTestSec ? 'text' : 'password'}
                              value={stripeTestSec}
                              onChange={(e) => setStripeTestSec(e.target.value)}
                              placeholder="sk_test_..."
                              className="w-full px-3.5 py-2.5 pr-20 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <div className="absolute right-2 flex items-center gap-1">
                              <button
                                type="button"
                                onClick={() => setShowStripeTestSec(!showStripeTestSec)}
                                title={showStripeTestSec ? 'Hide Key' : 'Unhide Key'}
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {showStripeTestSec ? <EyeOff className="w-4 h-4 text-amber-600" /> : <Eye className="w-4 h-4" />}
                              </button>
                              <button
                                type="button"
                                onClick={() => copyToClipboard(stripeTestSec, 'stripeTestSec', 'Test Secret Key')}
                                title="Copy key"
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {copiedField === 'stripeTestSec' ? (
                                  <Check className="w-4 h-4 text-emerald-600" />
                                ) : (
                                  <Copy className="w-4 h-4" />
                                )}
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* LIVE MODE SECTION */}
                  {stripeMode === 'live' && (
                    <div className="p-6 rounded-2xl bg-gray-50/80 border border-gray-200/60 space-y-4">
                      <div className="flex items-center gap-2 text-emerald-900 text-xs font-bold">
                        <KeyRound className="w-4 h-4 text-emerald-600" />
                        <span>Stripe Production Live Credentials</span>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        {/* Live Publishable Key */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Live Publishable Key
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type="text"
                              value={stripeLivePub}
                              onChange={(e) => setStripeLivePub(e.target.value)}
                              placeholder="pk_live_..."
                              className="w-full px-3.5 py-2.5 pr-11 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <button
                              type="button"
                              onClick={() => copyToClipboard(stripeLivePub, 'stripeLivePub', 'Live Publishable Key')}
                              title="Copy key"
                              className="absolute right-2 p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                            >
                              {copiedField === 'stripeLivePub' ? (
                                <Check className="w-4 h-4 text-emerald-600" />
                              ) : (
                                <Copy className="w-4 h-4" />
                              )}
                            </button>
                          </div>
                        </div>

                        {/* Live Secret Key */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Live Secret Key
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type={showStripeLiveSec ? 'text' : 'password'}
                              value={stripeLiveSec}
                              onChange={(e) => setStripeLiveSec(e.target.value)}
                              placeholder="sk_live_..."
                              className="w-full px-3.5 py-2.5 pr-20 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <div className="absolute right-2 flex items-center gap-1">
                              <button
                                type="button"
                                onClick={() => setShowStripeLiveSec(!showStripeLiveSec)}
                                title={showStripeLiveSec ? 'Hide Key' : 'Unhide Key'}
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {showStripeLiveSec ? <EyeOff className="w-4 h-4 text-emerald-600" /> : <Eye className="w-4 h-4" />}
                              </button>
                              <button
                                type="button"
                                onClick={() => copyToClipboard(stripeLiveSec, 'stripeLiveSec', 'Live Secret Key')}
                                title="Copy key"
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {copiedField === 'stripeLiveSec' ? (
                                  <Check className="w-4 h-4 text-emerald-600" />
                                ) : (
                                  <Copy className="w-4 h-4" />
                                )}
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* PAYPAL PAYMENT GATEWAY CARD */}
              <div className="bg-white rounded-3xl border border-gray-200/80 shadow-xs overflow-hidden transition-all duration-200 hover:shadow-md">
                <div className="p-6 border-b border-gray-100 bg-gradient-to-r from-blue-50/40 via-white to-transparent flex flex-wrap items-center justify-between gap-4">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-blue-600/10 text-blue-700 border border-blue-200/60 flex items-center justify-center font-bold shadow-xs">
                      <CreditCard className="w-6 h-6" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2.5">
                        <h2 className="text-lg font-black text-gray-900 tracking-tight">PayPal Payments</h2>
                        <span
                          className={`inline-flex items-center gap-1.5 px-3 py-0.5 rounded-full text-xs font-bold tracking-wide transition-colors ${paypalMode === 'live'
                            ? 'bg-emerald-50 text-emerald-700 border border-emerald-200/60'
                            : 'bg-amber-50 text-amber-700 border border-amber-200/60'
                            }`}
                        >
                          <span
                            className={`w-2 h-2 rounded-full ${paypalMode === 'live' ? 'bg-emerald-500' : 'bg-amber-500'}`}
                          />
                          {paypalMode === 'live' ? 'Live Mode' : 'Sandbox Mode'}
                        </span>
                      </div>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Accept PayPal balance and card payments through standard PayPal checkout.
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => setPaypalEnabled(!paypalEnabled)}
                      className={`relative inline-flex h-7 w-12 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${paypalEnabled ? 'bg-emerald-500' : 'bg-gray-300'
                        }`}
                      role="switch"
                      aria-checked={paypalEnabled}
                    >
                      <span
                        className={`pointer-events-none inline-block h-6 w-6 transform rounded-full bg-white shadow-md ring-0 transition duration-200 ease-in-out ${paypalEnabled ? 'translate-x-5' : 'translate-x-0'
                          }`}
                      />
                    </button>
                    <span className="text-xs font-extrabold text-gray-700">
                      {paypalEnabled ? 'Enabled' : 'Disabled'}
                    </span>
                  </div>
                </div>

                <div className="p-6 space-y-6">
                  {/* Environment Switcher */}
                  <div>
                    <label className="block text-xs font-extrabold uppercase tracking-wider text-gray-500 mb-2">
                      Active Environment Mode
                    </label>
                    <div className="grid grid-cols-2 gap-3 max-w-md p-1 bg-gray-100/90 rounded-2xl border border-gray-200/70">
                      <button
                        type="button"
                        onClick={() => setPaypalMode('test')}
                        className={`py-2.5 px-4 rounded-xl text-xs font-bold transition flex items-center justify-center gap-2 ${paypalMode === 'test'
                          ? 'bg-white text-gray-900 shadow-sm font-extrabold border border-gray-200'
                          : 'text-gray-500 hover:text-gray-800'
                          }`}
                      >
                        <span className="w-2 h-2 rounded-full bg-amber-500" />
                        <span>Sandbox Test</span>
                      </button>
                      <button
                        type="button"
                        onClick={() => setPaypalMode('live')}
                        className={`py-2.5 px-4 rounded-xl text-xs font-bold transition flex items-center justify-center gap-2 ${paypalMode === 'live'
                          ? 'bg-white text-gray-900 shadow-sm font-extrabold border border-gray-200'
                          : 'text-gray-500 hover:text-gray-800'
                          }`}
                      >
                        <span className="w-2 h-2 rounded-full bg-emerald-500" />
                        <span>Live Mode</span>
                      </button>
                    </div>
                  </div>

                  {/* PAYPAL TEST MODE SECTION */}
                  {paypalMode === 'test' && (
                    <div className="p-6 rounded-2xl bg-gray-50/80 border border-gray-200/60 space-y-4">
                      <div className="flex items-center gap-2 text-amber-900 text-xs font-bold">
                        <KeyRound className="w-4 h-4 text-amber-600" />
                        <span>PayPal Sandbox Credentials</span>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        {/* Sandbox Client ID */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Sandbox Client ID
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type="text"
                              value={paypalTestClientId}
                              onChange={(e) => setPaypalTestClientId(e.target.value)}
                              placeholder="PayPal Sandbox Client ID"
                              className="w-full px-3.5 py-2.5 pr-11 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <button
                              type="button"
                              onClick={() => copyToClipboard(paypalTestClientId, 'paypalTestClientId', 'Sandbox Client ID')}
                              title="Copy ID"
                              className="absolute right-2 p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                            >
                              {copiedField === 'paypalTestClientId' ? (
                                <Check className="w-4 h-4 text-emerald-600" />
                              ) : (
                                <Copy className="w-4 h-4" />
                              )}
                            </button>
                          </div>
                        </div>

                        {/* Sandbox Client Secret */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Sandbox Client Secret
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type={showPaypalTestSecret ? 'text' : 'password'}
                              value={paypalTestClientSecret}
                              onChange={(e) => setPaypalTestClientSecret(e.target.value)}
                              placeholder="PayPal Sandbox Client Secret"
                              className="w-full px-3.5 py-2.5 pr-20 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <div className="absolute right-2 flex items-center gap-1">
                              <button
                                type="button"
                                onClick={() => setShowPaypalTestSecret(!showPaypalTestSecret)}
                                title={showPaypalTestSecret ? 'Hide Secret' : 'Unhide Secret'}
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {showPaypalTestSecret ? <EyeOff className="w-4 h-4 text-amber-600" /> : <Eye className="w-4 h-4" />}
                              </button>
                              <button
                                type="button"
                                onClick={() => copyToClipboard(paypalTestClientSecret, 'paypalTestClientSecret', 'Sandbox Client Secret')}
                                title="Copy secret"
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {copiedField === 'paypalTestClientSecret' ? (
                                  <Check className="w-4 h-4 text-emerald-600" />
                                ) : (
                                  <Copy className="w-4 h-4" />
                                )}
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* PAYPAL LIVE MODE SECTION */}
                  {paypalMode === 'live' && (
                    <div className="p-6 rounded-2xl bg-gray-50/80 border border-gray-200/60 space-y-4">
                      <div className="flex items-center gap-2 text-emerald-900 text-xs font-bold">
                        <KeyRound className="w-4 h-4 text-emerald-600" />
                        <span>PayPal Production Live Credentials</span>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        {/* Live Client ID */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Live Client ID
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type="text"
                              value={paypalLiveClientId}
                              onChange={(e) => setPaypalLiveClientId(e.target.value)}
                              placeholder="PayPal Live Client ID"
                              className="w-full px-3.5 py-2.5 pr-11 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <button
                              type="button"
                              onClick={() => copyToClipboard(paypalLiveClientId, 'paypalLiveClientId', 'Live Client ID')}
                              title="Copy ID"
                              className="absolute right-2 p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                            >
                              {copiedField === 'paypalLiveClientId' ? (
                                <Check className="w-4 h-4 text-emerald-600" />
                              ) : (
                                <Copy className="w-4 h-4" />
                              )}
                            </button>
                          </div>
                        </div>

                        {/* Live Client Secret */}
                        <div>
                          <label className="block text-xs font-bold text-gray-700 mb-1.5">
                            Live Client Secret
                          </label>
                          <div className="relative flex items-center">
                            <input
                              type={showPaypalLiveSecret ? 'text' : 'password'}
                              value={paypalLiveClientSecret}
                              onChange={(e) => setPaypalLiveClientSecret(e.target.value)}
                              placeholder="PayPal Live Client Secret"
                              className="w-full px-3.5 py-2.5 pr-20 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none bg-white transition"
                            />
                            <div className="absolute right-2 flex items-center gap-1">
                              <button
                                type="button"
                                onClick={() => setShowPaypalLiveSecret(!showPaypalLiveSecret)}
                                title={showPaypalLiveSecret ? 'Hide Secret' : 'Unhide Secret'}
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {showPaypalLiveSecret ? <EyeOff className="w-4 h-4 text-emerald-600" /> : <Eye className="w-4 h-4" />}
                              </button>
                              <button
                                type="button"
                                onClick={() => copyToClipboard(paypalLiveClientSecret, 'paypalLiveClientSecret', 'Live Client Secret')}
                                title="Copy secret"
                                className="p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              >
                                {copiedField === 'paypalLiveClientSecret' ? (
                                  <Check className="w-4 h-4 text-emerald-600" />
                                ) : (
                                  <Copy className="w-4 h-4" />
                                )}
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* BANK TRANSFER CARD */}
              <div className="bg-white rounded-3xl border border-gray-200/80 shadow-xs overflow-hidden transition-all duration-200 hover:shadow-md">
                <div className="p-6 border-b border-gray-100 bg-gradient-to-r from-teal-50/40 via-white to-transparent flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-teal-600/10 text-teal-700 border border-teal-200/60 flex items-center justify-center font-bold shadow-xs">
                      <Building2 className="w-6 h-6" />
                    </div>
                    <div>
                      <h2 className="text-lg font-black text-gray-900 tracking-tight">Direct Bank Transfer</h2>
                      <p className="text-xs text-gray-500 mt-0.5">
                        Allow manual wire transfer payments with receipt verification by admin.
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => setBankEnabled(!bankEnabled)}
                      className={`relative inline-flex h-7 w-12 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${bankEnabled ? 'bg-emerald-500' : 'bg-gray-300'
                        }`}
                      role="switch"
                      aria-checked={bankEnabled}
                    >
                      <span
                        className={`pointer-events-none inline-block h-6 w-6 transform rounded-full bg-white shadow-md ring-0 transition duration-200 ease-in-out ${bankEnabled ? 'translate-x-5' : 'translate-x-0'
                          }`}
                      />
                    </button>
                    <span className="text-xs font-extrabold text-gray-700">
                      {bankEnabled ? 'Enabled' : 'Disabled'}
                    </span>
                  </div>
                </div>

                <div className="p-6 space-y-5">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-1.5">
                        Bank Name
                      </label>
                      <input
                        type="text"
                        value={bankName}
                        onChange={(e) => setBankName(e.target.value)}
                        placeholder="e.g. Deutsche Bank AG"
                        className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-xs font-semibold focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none transition bg-white"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-1.5">
                        Account Holder Name
                      </label>
                      <input
                        type="text"
                        value={accountHolder}
                        onChange={(e) => setAccountHolder(e.target.value)}
                        placeholder="e.g. ApkaGermanSchool GmbH"
                        className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-xs font-semibold focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none transition bg-white"
                      />
                    </div>

                    {/* IBAN */}
                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-1.5">
                        IBAN / Account Number
                      </label>
                      <div className="relative flex items-center">
                        <input
                          type="text"
                          value={iban}
                          onChange={(e) => setIban(e.target.value)}
                          placeholder="DE89 3704 0044 0532 0130 00"
                          className="w-full px-3.5 py-2.5 pr-11 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none transition bg-white"
                        />
                        <button
                          type="button"
                          onClick={() => copyToClipboard(iban, 'bankIban', 'IBAN')}
                          title="Copy IBAN"
                          className="absolute right-2 p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                        >
                          {copiedField === 'bankIban' ? (
                            <Check className="w-4 h-4 text-emerald-600" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>

                    {/* SWIFT / BIC */}
                    <div>
                      <label className="block text-xs font-bold text-gray-700 mb-1.5">
                        SWIFT / BIC Code
                      </label>
                      <div className="relative flex items-center">
                        <input
                          type="text"
                          value={bicSwift}
                          onChange={(e) => setBicSwift(e.target.value)}
                          placeholder="DEUTDEDDBXX"
                          className="w-full px-3.5 py-2.5 pr-11 rounded-xl border border-gray-300 text-xs font-mono focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none transition bg-white"
                        />
                        <button
                          type="button"
                          onClick={() => copyToClipboard(bicSwift, 'bankBic', 'SWIFT/BIC Code')}
                          title="Copy BIC"
                          className="absolute right-2 p-1.5 text-gray-400 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                        >
                          {copiedField === 'bankBic' ? (
                            <Check className="w-4 h-4 text-emerald-600" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>

                    <div className="md:col-span-2">
                      <label className="block text-xs font-bold text-gray-700 mb-1.5">
                        Payment Instructions for Students
                      </label>
                      <textarea
                        rows={3}
                        value={paymentInstructions}
                        onChange={(e) => setPaymentInstructions(e.target.value)}
                        placeholder="Instructions shown to student on checkout page..."
                        className="w-full p-3.5 rounded-xl border border-gray-300 text-xs focus:border-[#FECE00] focus:ring-2 focus:ring-[#FECE00]/20 outline-none transition leading-relaxed bg-white"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* TAB 2: Privacy Policy */}
          {activeTab === 'privacy' && (
            <div className="bg-white rounded-3xl border border-gray-200/80 shadow-xs overflow-hidden">
              <div className="p-6 border-b border-gray-100 bg-gradient-to-r from-emerald-50/40 via-white to-transparent flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 border border-emerald-100 flex items-center justify-center">
                  <ShieldCheck className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-base font-extrabold text-gray-900">Privacy Policy Document</h2>
                  <p className="text-xs text-gray-500">
                    Edit the Privacy Policy text displayed to visitors and students. Markdown formatted.
                  </p>
                </div>
              </div>

              <div className="p-6 space-y-4">
                <div>
                  <label className="block text-xs font-bold uppercase text-gray-700 mb-2">
                    Privacy Policy Content
                  </label>
                  <RichTextEditor
                    value={privacyPolicy}
                    onChange={(val) => setPrivacyPolicy(val)}
                    placeholder="Enter Privacy Policy content here..."
                  />
                </div>
              </div>
            </div>
          )}

          {/* TAB 3: Terms & Conditions */}
          {activeTab === 'terms' && (
            <div className="bg-white rounded-3xl border border-gray-200/80 shadow-xs overflow-hidden">
              <div className="p-6 border-b border-gray-100 bg-gradient-to-r from-blue-50/40 via-white to-transparent flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 border border-blue-100 flex items-center justify-center">
                  <FileText className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-base font-extrabold text-gray-900">Terms & Conditions Document</h2>
                  <p className="text-xs text-gray-500">
                    Edit the Terms & Conditions agreement displayed during registration and checkout. Markdown formatted.
                  </p>
                </div>
              </div>

              <div className="p-6 space-y-4">
                <div>
                  <label className="block text-xs font-bold uppercase text-gray-700 mb-2">
                    Terms & Conditions Content
                  </label>
                  <RichTextEditor
                    value={termsAndConditions}
                    onChange={(val) => setTermsAndConditions(val)}
                    placeholder="Enter Terms & Conditions content here..."
                  />
                </div>
              </div>
            </div>
          )}

          {/* Save Action Button */}
          <div className="flex justify-end pt-4">
            <button
              type="submit"
              disabled={saving}
              className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center gap-2 cursor-pointer disabled:opacity-50"
            >
              <Save className="w-4 h-4 text-black" />
              <span>
                {saving
                  ? 'Saving Settings...'
                  : activeTab === 'system'
                    ? 'Save Payment Configurations'
                    : activeTab === 'privacy'
                      ? 'Save Privacy Policy'
                      : 'Save Terms & Conditions'}
              </span>
            </button>
          </div>
        </form>
      )}
    </div>
  );
}
