import React, { useState, useRef, useEffect } from 'react';
import type { DashboardData } from './types';
import {
  Key,
  ShieldCheck,
  CheckCircle2,
  ExternalLink,
  Loader2,
  Save,
  Shield,
  Zap,
  Lock,
  ShoppingBag,
  UserPlus,
  RefreshCw,
  Sparkles
} from 'lucide-react';
import ReCAPTCHA from "react-google-recaptcha";

import {
  SettingCard,
  FlatTabs,
  ModernCardHeader,
  SettingInput,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SecondaryButton,
  FeatSection,
  FeatRow,
  StatusMessage
} from './components/ui/settings-ui';
import { toast } from "sonner";
import { motion, AnimatePresence } from "framer-motion";
import { CompactSettingCard } from './components/ui/CompactSettingCard';

interface RecaptchaSettings {
  site_key: string;
  secret_key: string;
  type: string;
  score: string;
  enable_login: number;
  enable_register: number;
  enable_lostpassword: number;
  enable_checkout: number;
  enable_wawp_login: number;
  enable_wawp_signup: number;
}

interface RecaptchaData {
  settings: RecaptchaSettings;
  replaceWcFormsActive: number;
  nonce: string;
  ajaxUrl: string;
  i18n: {
    [key: string]: string;
  };
  optionNames?: { [key: string]: string };
}

const GoogleRecaptchaSettings: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = rootData?.recaptchaData as RecaptchaData;
  const recaptchaRef = useRef<ReCAPTCHA>(null);

  const [activeTab, setActiveTab] = useState('general');
  const [settings, setSettings] = useState(data?.settings || {} as RecaptchaSettings);
  const [isSaving, setIsSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [testStatus, setTestStatus] = useState<{ message: string; type: 'idle' | 'testing' | 'success' | 'error' }>({ message: '', type: 'idle' });

  // Adjust state during render if props change
  const [prevData, setPrevData] = useState(data);
  if (data !== prevData) {
    setPrevData(data);
    if (data?.settings) {
      setSettings(data.settings);
    }
  }

  const t = React.useCallback((key: string, fallback: string = ''): string => {
    const val = (data?.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  }, [data?.i18n]);
  
  const getStatus = (id: string): { type: 'active' | 'inactive' | 'error' | 'warning', message: string } | null => {
    switch (id) {
      case 'credentials':
        return (settings.site_key && settings.secret_key)
          ? { type: 'active', message: "reCAPTCHA credentials are configured and ready for validation." }
          : { type: 'error', message: "Site Key and Secret Key are required to enable bot protection." };
      case 'protection': {
        const enabledRules = [
          'enable_login', 'enable_register', 'enable_lostpassword', 
          'enable_checkout', 'enable_wawp_login', 'enable_wawp_signup'
        ].filter(key => settings[key as keyof RecaptchaSettings] == 1).length;
        
        return enabledRules > 0
          ? { type: 'active', message: `Protection is active on <b>${enabledRules}</b> specific forms.` }
          : { type: 'warning', message: "No protection rules are enabled. Your forms are currently vulnerable to bots." };
      }
      default: return null;
    }
  };

  const handleSave = React.useCallback(async (silent = true) => {
    if (!silent) setIsSaving(true);
    setSaveStatus('saving');

    try {
      const settingsToSave: Record<string, unknown> = {};

      // Map frontend keys to database option names via optionNames map
      Object.keys(settings).forEach(key => {
        const dbKey = data?.optionNames?.[key] || key;
        settingsToSave[dbKey] = settings[key as keyof RecaptchaSettings];
      });

      const response = await fetch(rootData?.global?.settingsRestUrl || '', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': rootData?.global?.wpRestNonce || ''
        },
        body: JSON.stringify({
          settings: settingsToSave
        })
      });

      if (response.ok) {
        setHasUnsavedChanges(false);
        setSaveStatus('saved');
        window.dispatchEvent(new CustomEvent('wawp-refresh-data'));
        if (!silent) toast.success(t('settingsSaved', "Security configuration synchronized successfully."));
        setTimeout(() => setSaveStatus('idle'), 3000);
      } else {
        const result = await response.json();
        setSaveStatus('error');
        if (!silent) toast.error(result.message || "Synchronization failed.");
      }
    } catch (error) {
      console.error('Recaptcha save error:', error);
      setSaveStatus('error');
      if (!silent) toast.error("Network error during synchronization.");
    } finally {
      if (!silent) setIsSaving(false);
    }
  }, [settings, data, rootData, t]);

  const updateSetting = <K extends keyof RecaptchaSettings>(key: K, value: RecaptchaSettings[K]) => {
    setSettings(prev => ({ ...prev, [key]: value }));
    setHasUnsavedChanges(true);
  };

  useEffect(() => {
    if (!hasUnsavedChanges) return;

    const timer = setTimeout(() => {
      handleSave();
    }, 1500);

    return () => clearTimeout(timer);
  }, [settings, hasUnsavedChanges, handleSave]);

  if (!data) return null;


  const tabs = [
    { id: 'general', label: t('generalSettings', 'Configuration'), icon: Key },
    { id: 'protection', label: t('protectionRules', 'Security Rules'), icon: ShieldCheck },
  ];

  const onTestCaptcha = (token: string | null) => {
    if (!token) return;
    setTestStatus({ message: 'Verifying with Google...', type: 'testing' });

    setTimeout(() => {
      setTestStatus({ message: 'Success! Your reCAPTCHA configuration is valid and active.', type: 'success' });
    }, 1500);
  };

  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-6">
        <SettingsHeader
        title={t('recaptchaSettingsTitle', 'Google reCAPTCHA')}
        description={t('recaptchaSettingsDesc', 'Configure anti-bot protection for your authentication and checkout forms.')}
      >
        <div className="flex items-center gap-3">
          <SecondaryButton onClick={() => window.open('https://www.google.com/recaptcha/admin', '_blank')} className="uppercase tracking-widest text-[11px] font-black" icon={ExternalLink}>
            Google Console
          </SecondaryButton>

          <AnimatePresence mode="wait">
            {saveStatus === 'saving' && (
              <motion.div
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                className="flex items-center gap-2 px-3 py-1.5 bg-indigo-50 text-indigo-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-indigo-100/50"
              >
                <span className="w-1.5 h-1.5 bg-indigo-500 rounded-full animate-pulse" />
                Synchronizing...
              </motion.div>
            )}
            {saveStatus === 'saved' && (
              <motion.div
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                className="flex items-center gap-2 px-3 py-1.5 bg-emerald-50 text-emerald-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-emerald-100/50"
              >
                <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full" />
                Secured
              </motion.div>
            )}
            {hasUnsavedChanges && saveStatus === 'idle' && (
              <motion.div
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                className="flex items-center gap-2 px-3 py-1.5 bg-amber-50 text-amber-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-amber-100/50"
              >
                <span className="w-1.5 h-1.5 bg-amber-500 rounded-full animate-ping" />
                Pending Commit
              </motion.div>
            )}
          </AnimatePresence>

          <AdminButton
            onClick={() => handleSave(false)}
            loading={isSaving}
            icon={Save}
            className="px-6"
          >
            {isSaving ? 'Synchronizing...' : 'Commit Security'}
          </AdminButton>
        </div>
      </SettingsHeader>

      <FlatTabs
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />

      <div className="space-y-8">
        <AnimatePresence mode="wait">
          <motion.div
            key={activeTab}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            transition={{ duration: 0.3 }}
            className="space-y-8"
          >
            {activeTab === 'general' && (
              <div className="space-y-8 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden shadow-none">
                  <ModernCardHeader
                    title="API Credentials"
                    description="Enter your Google reCAPTCHA v2 (Check) or v3 (Invisible) keys."
                    icon={Shield}
                  />
                  <div className="p-6 md:p-8 space-y-8">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                      <SettingInput
                        label="Site Key"
                        value={settings.site_key}
                        onChange={(val: string) => {
                          setSettings({ ...settings, site_key: val });
                          setHasUnsavedChanges(true);
                        }}
                        placeholder=""
                        icon={Key}
                      />
                      <SettingInput
                        label="Secret Key"
                        value={settings.secret_key}
                        onChange={(val: string) => {
                          setSettings({ ...settings, secret_key: val });
                          setHasUnsavedChanges(true);
                        }}
                        placeholder=""
                        type="password"
                        icon={Lock}
                      />
                    </div>

                    <div className="flex flex-col md:flex-row gap-8 items-start">
                      <div className="flex-1 space-y-3">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">reCAPTCHA Version</label>
                        <div className="flex gap-4 p-1.5 bg-slate-50/50 border border-slate-200 rounded-xl w-fit">
                          {[
                            { id: 'v2_invisible', label: t('v2Invisible', 'v2 Invisible') },
                            { id: 'v2_checkbox', label: t('v2Checkbox', 'v2 Checkbox') }
                          ].map(v => (
                            <button
                              key={v.id}
                              onClick={() => updateSetting('type', v.id)}
                              className={`px-8 py-2.5 rounded-lg text-[11px] font-black uppercase tracking-widest transition-all ${settings.type === v.id ? 'bg-[#004449] text-white shadow-md' : 'text-slate-400 hover:text-slate-600'}`}
                            >
                              {v.label}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                    {getStatus('credentials') && <StatusMessage {...getStatus('credentials')!} className="mt-6" />}
                  </div>
                </SettingCard>

                <CompactSettingCard
                  title="Configuration Validation"
                  description="Test your integration directly before enabling it on live forms."
                  icon={RefreshCw}
                  hideSwitch={true}
                >
                  <div className="flex flex-col items-center justify-center text-center space-y-8">
                    <div className="min-h-[100px] flex flex-col items-center justify-center gap-6">
                      {settings.site_key ? (
                        <>
                          <ReCAPTCHA
                            key={`${settings.site_key}-${settings.type}`}
                            ref={recaptchaRef}
                            sitekey={settings.site_key}
                            size={settings.type === 'v2_invisible' ? 'invisible' : 'normal'}
                            onChange={onTestCaptcha}
                          />
                          {settings.type === 'v2_invisible' && (
                            <SecondaryButton
                              onClick={() => recaptchaRef.current?.execute()}
                              className="text-[10px] font-black uppercase tracking-widest px-6 h-9"
                              icon={Zap}
                            >
                              Trigger Invisible Challenge
                            </SecondaryButton>
                          )}
                        </>
                      ) : (
                        <div className="p-6 border border-dashed border-slate-200 rounded-xl text-slate-400 text-sm font-medium">
                          {t('keysRequired', 'Enter a site key to load the test widget.')}
                        </div>
                      )}
                    </div>

                    {testStatus.type !== 'idle' && (
                      <div className={`p-4 rounded-xl border flex items-center gap-3 animate-in zoom-in-95 duration-300 ${testStatus.type === 'success' ? 'bg-emerald-50 border-emerald-100 text-emerald-700' : 'bg-slate-50 border-slate-200 text-slate-600'}`}>
                        {testStatus.type === 'testing' ? <Loader2 size={16} className="animate-spin" /> : <CheckCircle2 size={16} />}
                        <span className="text-xs font-bold leading-tight">{testStatus.message}</span>
                      </div>
                    )}
                  </div>
                </CompactSettingCard>
              </div>
            )}

            {activeTab === 'protection' && (
              <FeatSection
                title={t('protectionRules', 'Security Rules')}
                description={t('recaptchaRulesDesc', 'Enable anti-bot protection for specific forms across your site.')}
                icon={ShieldCheck}
                gridCols="grid-cols-1 md:grid-cols-2"
              >
                {[
                  { key: 'enable_login', label: t('enableFormLogin', 'WordPress Login'), icon: Lock, desc: 'Protects the standard /wp-login.php page.' },
                  { key: 'enable_register', label: t('enableFormRegister', 'WordPress Registration'), icon: UserPlus, desc: 'Prevents bot accounts on default signup page.' },
                  { key: 'enable_lostpassword', label: t('enableFormLostPass', 'Lost Password'), icon: Key, desc: 'Blocks brute-force reset requests.' },
                  { key: 'enable_checkout', label: t('enableFormCheckout', 'WooCommerce Checkout'), icon: ShoppingBag, desc: 'Halts fake orders and carding attacks.' },
                  { key: 'enable_wawp_login', label: 'Wawp OTP Login', icon: Zap, desc: 'Secures custom single-use code login form.' },
                  { key: 'enable_wawp_signup', label: 'Wawp Registration', icon: Sparkles, desc: 'Adds reCAPTCHA to WAWP custom builders.' }
                ].map((rule) => {
                  const isWC = rule.key === 'enable_checkout';
                  const isWCInactive = isWC && data.replaceWcFormsActive == 0;
                  const isEnabled = settings[rule.key as keyof RecaptchaSettings] == 1;

                  return (
                    <FeatRow
                      key={rule.key}
                      icon={rule.icon}
                      title={rule.label}
                      desc={rule.desc}
                      enabled={isEnabled}
                      allowed={true}
                      error={isWCInactive ? 'Requires WooCommerce Forms' : undefined}
                      onToggle={() => updateSetting(rule.key as keyof RecaptchaSettings, isEnabled ? 0 : 1)}
                    />
                  );
                })}
                <div className="mt-6">
                  {getStatus('protection') && <StatusMessage {...getStatus('protection')!} />}
                </div>
              </FeatSection>
            )}
          </motion.div>
        </AnimatePresence>
      </div>
    </div>
  </SettingsLayout>
  );
};

export default GoogleRecaptchaSettings;
