import React, { useState } from 'react';
import type { DashboardData, WhatsAppInstance } from './types';
import {
  ShoppingBasket,
  Settings2,
  Palette,
  Save,
  Brackets,
  Globe,
  MessageSquare,
  Mail,
  Flame,
  ExternalLink,
  Lock,
  Type
} from 'lucide-react';
import { motion, AnimatePresence } from "framer-motion";
import { Switch } from './components/ui/switch';
import { Label } from './components/ui/label';
import { PersonalizationDialog } from './components/ui/personalization-dialog';
import { SearchableSelect } from './components/ui/searchable-select';
import { Badge } from './components/ui/badge';
import WhatsAppAuthSettings from './components/common/WhatsAppAuthSettings';
import {
  SettingCard,
  FlatTabs,
  ModernCardHeader,
  StatusMessage,
  SettingInput,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  HeaderSaveStatus,
  MethodButton
} from './components/ui/settings-ui';

import { useSettingsManager, type ModuleData } from './hooks/use-settings-manager';

interface CheckoutVerificationData {
  options: Record<string, unknown>;
  paymentGateways: Array<{ id: string; title: string }>;
  shippingMethods: Record<string, string>;
   instances: WhatsAppInstance[];
  i18n: Record<string, string>;
  optionNames: Record<string, string>;
  availability?: {
    firebase?: {
      available: boolean;
    };
  };
}

const CheckoutVerificationSettings: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = React.useMemo<CheckoutVerificationData>(() => (rootData?.checkoutVerificationSettings || {
    options: {},
    paymentGateways: [],
    shippingMethods: {},
    instances: [],
    i18n: {},
    optionNames: {}
  }) as CheckoutVerificationData, [rootData?.checkoutVerificationSettings]);
  const msgs = rootData?.status_messages || {};

  const [activeTab, setActiveTab] = useState('general');

  const {
    settings,
    setSettings,
    updateSetting: handleChange,
    handleSave,
    saveStatus,
    hasUnsavedChanges,
    setHasUnsavedChanges,
    isSaving
  } = useSettingsManager<Record<string, unknown>>({
    rootData,
    moduleData: data as unknown as ModuleData,
    initialSettings: data.options || {}
  });

  const [isPersonalizationOpen, setIsPersonalizationOpen] = useState(false);
  const [personalizationEditorId, setPersonalizationEditorId] = useState('');

  const getStatus = (id: string): { type: 'active' | 'inactive' | 'error' | 'warning', message: string } | null => {
    switch (id) {
      case 'checkout_otp': {
        return {
          type: settings.wawp_enable_otp === 'yes' ? 'active' : 'inactive',
          message: settings.wawp_enable_otp === 'yes' ? (msgs.checkout_active || '') : (msgs.checkout_inactive || '')
        };
      }
      case 'otp_mode': {
        let modeDesc = '';
        if (settings.wawp_otp_mode === 'enable_for_all') modeDesc = msgs.checkout_mode_all || '';
        else if (settings.wawp_otp_mode === 'enable_for_guests') modeDesc = msgs.checkout_mode_guests || '';
        else if (settings.wawp_otp_mode === 'enable_for_loggedin') modeDesc = msgs.checkout_mode_loggedin || '';
        return { type: 'active', message: modeDesc };
      }
      case 'payment_exclusions': {
        const payCount = (settings.wawp_disable_otp_for_payment_methods as string[] || []).length;
        const payMsg = payCount > 0
          ? (msgs.checkout_pay_excl || '').replace('%d', payCount.toString())
          : (msgs.checkout_pay_all || '');
        return { type: 'active', message: payMsg };
      }
      case 'shipping_exclusions': {
        const shipCount = (settings.wawp_disable_otp_for_shipping_methods as string[] || []).length;
        const shipMsg = shipCount > 0
          ? (msgs.checkout_ship_excl || '').replace('%d', shipCount.toString())
          : (msgs.checkout_ship_all || '');
        return { type: 'active', message: shipMsg };
      }
      case 'checkout_otp_method': {
        let methodDesc = '';
        if (settings.wawp_checkout_otp_method === 'whatsapp') methodDesc = msgs.checkout_method_whatsapp || '';
        else if (settings.wawp_checkout_otp_method === 'email') methodDesc = msgs.checkout_method_email || '';
        else if (settings.wawp_checkout_otp_method === 'firebase') methodDesc = msgs.checkout_method_firebase || '';
        return { type: 'active', message: methodDesc };
      }
      case 'guest_checkout': {
        return {
          type: settings.woocommerce_enable_guest_checkout === 'yes' ? 'active' : 'inactive',
          message: settings.woocommerce_enable_guest_checkout === 'yes' ? (msgs.checkout_guest_a || '') : (msgs.checkout_guest_i || '')
        };
      }
      case 'login_reminder': {
        return {
          type: settings.woocommerce_enable_checkout_login_reminder === 'yes' ? 'active' : 'inactive',
          message: settings.woocommerce_enable_checkout_login_reminder === 'yes' ? (msgs.checkout_login_a || '') : (msgs.checkout_login_i || '')
        };
      }
      case 'account_creation': {
        return {
          type: settings.woocommerce_enable_signup_and_login_from_checkout === 'yes' ? 'active' : 'inactive',
          message: settings.woocommerce_enable_signup_and_login_from_checkout === 'yes' ? (msgs.checkout_signup_a || '') : (msgs.checkout_signup_i || '')
        };
      }
      case 'password_setup': {
        return {
          type: settings.woocommerce_registration_generate_password === 'yes' ? 'active' : 'inactive',
          message: settings.woocommerce_registration_generate_password === 'yes' ? (msgs.checkout_pass_a || '') : (msgs.checkout_pass_i || '')
        };
      }
      default:
        return null;
    }
  };

  const handleToggle = (key: string) => {
    setSettings((prev: Record<string, unknown>) => ({ ...prev, [key]: prev[key] === 'yes' ? 'no' : 'yes' }));
    setHasUnsavedChanges(true);
  };

  const t = data.i18n || {};

  const tabs = [
    { id: 'general', label: t.general || 'General', icon: ShoppingBasket },
    { id: 'advanced', label: t.exclusions || 'Exclusions & Rules', icon: Settings2 },
    { id: 'style', label: t.style || 'Style & Branding', icon: Palette }
  ];

  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-6">
        <SettingsHeader
        title={t.checkout_title || "Checkout Verification"}
        description={t.checkout_desc || "Verify customers WhatsApp at checkout to prevent fraud & fake orders."}
      >
        <div className="flex items-center gap-3">
          <HeaderSaveStatus status={saveStatus === 'idle' && hasUnsavedChanges ? 'unsaved' : saveStatus} />

          <AdminButton
            onClick={() => handleSave(false)}
            loading={isSaving}
            icon={Save}
            className="px-10"
          >
            {isSaving ? 'Applying...' : (t.saveSettings || 'Save Settings')}
          </AdminButton>
        </div>
      </SettingsHeader>

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

      <div className="space-y-6">
        <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-6"
          >
            {activeTab === 'general' && (
              <div className="space-y-8 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.strategy_title || "Checkout OTP Strategy"}
                    description={t.strategy_desc || "Verify numbers to reduce fake cash-on-delivery orders. Compatible with all major payment gateways."}
                    icon={ShoppingBasket}
                    rightAction={
                      <Switch
                        checked={settings.wawp_enable_otp === 'yes'}
                        onCheckedChange={() => handleToggle('wawp_enable_otp')}
                      />
                    }
                  />

                  <div className="p-6 md:p-8 space-y-8">
                    <StatusMessage
                      type={settings.wawp_enable_otp === 'yes' ? 'active' : 'inactive'}
                      message={settings.wawp_enable_otp === 'yes' ? (msgs.checkout_active || 'Checkout verification is active') : (msgs.checkout_inactive || 'Checkout verification is paused')}
                    />

                    <div className="space-y-4">
                      <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Preferred Verification Channel</label>
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        {[
                          { id: 'whatsapp', label: 'WhatsApp Web Authentication', icon: MessageSquare, description: 'High-speed WhatsApp OTP & Interactive verification via your own WhatsApp instances.', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", color: 'text-emerald-600', bg: 'bg-emerald-50' },
                          { id: 'email', label: 'Email Magic Link Login', icon: Mail, description: 'Users receive a secure link in their inbox to authorize login instantly.', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg", color: 'text-blue-600', bg: 'bg-blue-50' },
                          { id: 'firebase', label: 'Firebase SMS Authentication', icon: Flame, description: 'Use Google Firebase to send SMS verification codes globally (Requires API Key).', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg", color: 'text-orange-600', bg: 'bg-orange-50' }
                        ].map(item => (
                          <MethodButton
                            key={item.id}
                            active={settings.wawp_checkout_otp_method === item.id}
                            onClick={() => handleChange('wawp_checkout_otp_method', item.id)}
                            label={item.label}
                            description={item.description}
                            icon={item.icon}
                            iconPath={item.iconPath}
                            color={item.color}
                            bg={item.bg}
                          />
                        ))}
                      </div>
                    </div>


                  </div>
                </SettingCard>

                {settings.wawp_checkout_otp_method === 'whatsapp' && (
                  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                    <SettingCard className="p-0 overflow-hidden">
                      <div className="p-6 md:p-8 space-y-6">
                        <div className="flex items-center gap-2 mb-2 pl-1">
                          <span className="text-[11px] font-black text-slate-400 uppercase tracking-widest">WhatsApp Auth Engine</span>
                          <Badge variant="outline" className="h-5 px-1.5 text-[9px] font-black border-slate-200 text-slate-500 uppercase ml-auto">Active</Badge>
                        </div>

                        <div className="space-y-6 pt-4 border-t border-slate-100">
                          <WhatsAppAuthSettings
                            settings={settings as Record<string, string | number | boolean>}
                            updateSetting={handleChange}
                            optionNames={data.optionNames}
                          />
                        </div>

                        <StatusMessage
                          type={settings.wawp_enable_otp === 'yes' ? 'active' : 'inactive'}
                          message={settings.wawp_enable_otp === 'yes' ? (msgs.checkout_active || 'Checkout verification is active') : (msgs.checkout_inactive || 'Checkout verification is paused')}
                        />
                      </div>
                    </SettingCard>
                  </motion.div>
                )}

                {settings.wawp_checkout_otp_method === 'email' && (
                  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title={t.email_magic_link_title || "Email Magic Link Login"}
                        description={t.email_magic_link_desc || "Users receive a secure link in their inbox to authorize login instantly."}
                        iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg"}
                      />
                      <div className="p-6 md:p-8 space-y-6">
                        <div className="flex items-center gap-2 mb-2 pl-1">
                          <Globe className="w-4 h-4 text-slate-400" />
                          <span className="text-[11px] font-black text-slate-400 uppercase tracking-widest">Customer Email</span>
                          <Badge variant="outline" className="h-5 px-1.5 text-[9px] font-black border-slate-200 text-slate-500 uppercase ml-auto">SMTP</Badge>
                        </div>


                        <SettingInput
                          label="Subject"
                          value={settings.wawp_otp_subject_email as string || ''}
                          onChange={(val) => handleChange('wawp_otp_subject_email', val)}
                          placeholder="Your verification code..."
                          icon={Mail}
                          showFormatting={false}
                          showEmoji={true}
                          button={
                            <button
                              className="p-2 text-slate-400 hover:text-blue-600 transition-colors border-none bg-transparent cursor-pointer"
                              onClick={() => {
                                setPersonalizationEditorId('wawp_otp_subject_email');
                                setIsPersonalizationOpen(true);
                              }}
                            >
                              <Brackets size={14} />
                            </button>
                          }
                        />

                        <div className="space-y-1.5 w-full">
                          <div className="flex justify-between items-center px-1">
                            <Label className="text-[11px] font-black text-slate-400 uppercase tracking-widest">Body Template</Label>
                            <a
                              href="/wp-admin/admin.php?page=wawp&wawp_section=email_templates"
                              className="text-[10px] font-black text-[#004449] hover:text-[#003337] uppercase tracking-widest flex items-center gap-1 transition-colors"
                              title="Manage Templates"
                            >
                              <Settings2 size={12} />
                              Manage
                            </a>
                          </div>
                          <SearchableSelect
                            options={(data as unknown as { emailTemplates: Array<{ id: number, name: string }> }).emailTemplates?.map(tpl => ({
                              value: tpl.id.toString(),
                              label: tpl.name
                            })) || (rootData?.registrationForm as unknown as { emailTemplates: Array<{ id: number, name: string }> })?.emailTemplates?.map(tpl => ({
                              value: tpl.id.toString(),
                              label: tpl.name
                            })) || []}
                            value={settings.wawp_otp_email_template_id?.toString() || ""}
                            onChange={(val) => handleChange('wawp_otp_email_template_id', val)}
                            placeholder="Select Email Template..."
                            className="h-11 bg-slate-50/30 border-slate-200 text-slate-700 font-bold text-[13px] hover:bg-white hover:border-[#004449]/30 transition-all rounded-[5px]"
                          />
                        </div>
                      </div>
                    </SettingCard>
                  </motion.div>
                )}

                {settings.wawp_checkout_otp_method === 'firebase' && (
                  <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title={t.firebase_sms_auth_title || "Firebase SMS Authentication"}
                        description={t.firebase_sms_auth_desc || "Use Google Firebase to send SMS verification codes globally (Requires API Key)."}
                        iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"}
                      />
                      <div className="p-6 md:p-8 flex flex-col md:flex-row items-center gap-6">
                        <div className="h-14 w-14 flex items-center justify-center shrink-0">
                          <img src={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"} className="w-10 h-10 object-contain" alt="" />
                        </div>
                        <div className="flex-1 space-y-1.5 text-center md:text-left">
                          <h5 className="font-extrabold text-slate-900 text-[15px]">{t.firebase_tpl_label || "Manage Firebase SMS Templates"}</h5>
                          <p className="text-[12px] text-slate-500 leading-relaxed font-medium max-w-xl">
                            Firebase SMS messages are handled externally. To modify templates or manage costs, please visit your Firebase control panel.
                          </p>
                        </div>
                        <a
                          href="https://console.firebase.google.com/" target="_blank"
                          className="shrink-0 px-6 py-2.5 bg-orange-600 hover:bg-orange-700 !text-white text-[12px] font-black rounded-[5px] transition-all flex items-center gap-2 shadow-none hover:shadow-lg hover:shadow-orange-100 active:scale-95"
                          style={{ color: 'white' }}
                        >
                          Open Firebase Console
                          <ExternalLink size={14} className="!text-white" style={{ color: 'white' }} />
                        </a>
                      </div>
                      <div className="px-6 md:px-8 pb-8">
                        <StatusMessage 
                          type={data.availability?.firebase?.available ? 'active' : 'warning'} 
                          message={data.availability?.firebase?.available ? "Firebase Account found. System is ready to route messages through Google gateway." : "<b>Firebase is not configured!</b> Please visit the Firebase Settings tab first."} 
                        />
                      </div>
                    </SettingCard>
                  </motion.div>
                )}
              </div>
            )}

            {activeTab === 'advanced' && (
              <div className="space-y-6 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.security_hardening || "Security Hardening"}
                    description={t.security_hardening_desc || "Define exactly when and for whom the verification triggers."}
                    icon={Lock}
                  />

                  <div className="p-6 md:p-8 space-y-6">
                    <div className="space-y-2">
                      <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">{t.otp_mode_label || "Verification Enforcement"}</label>
                      <SearchableSelect
                        options={[
                          { value: "enable_for_all", label: msgs.checkout_mode_all || "Verify all customers" },
                          { value: "enable_for_guests", label: msgs.checkout_mode_guests || "Verify guests only" },
                          { value: "enable_for_loggedin", label: msgs.checkout_mode_loggedin || "Verify logged-in users only" }
                        ]}
                        value={settings.wawp_otp_mode as string}
                        onChange={(val) => handleChange('wawp_otp_mode', val)}
                        className="h-11 bg-slate-50/50 border-slate-200 text-slate-700 font-bold text-[13px] hover:bg-white hover:border-[#004449]/30 transition-all rounded-[5px]"
                      />
                      <StatusMessage
                        type="active"
                        message={getStatus('otp_mode')?.message || ''}
                      />
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-6 border-t border-slate-50">
                      <div className="space-y-3">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1 flex items-center gap-2">
                          <Lock size={12} />
                          {t.payment_exclusions_title || "Exclude Payment Gateways"}
                        </label>
                        <div className="grid grid-cols-1 gap-2">
                          {(data.paymentGateways as Array<{ id: string, title: string }>)?.map(gate => (
                            <label key={gate.id} className={`flex items-center justify-between p-3 rounded-[5px] border transition-all cursor-pointer ${(settings.wawp_disable_otp_for_payment_methods as string[] || []).includes(gate.id)
                              ? 'border-blue-500 bg-blue-50/10' : 'border-slate-100 bg-white hover:border-slate-200'
                              }`}>
                              <span className="text-[13px] font-bold text-slate-700">{gate.title}</span>
                              <input
                                type="checkbox"
                                className="w-4 h-4 rounded border-slate-300 text-[#004449] focus:ring-[#004449]"
                                checked={(settings.wawp_disable_otp_for_payment_methods as string[] || []).includes(gate.id)}
                                onChange={(e) => {
                                  const current = settings.wawp_disable_otp_for_payment_methods as string[] || [];
                                  const next = e.target.checked
                                    ? [...current, gate.id]
                                    : current.filter((id: string) => id !== gate.id);
                                  handleChange('wawp_disable_otp_for_payment_methods', next);
                                }}
                              />
                            </label>
                          ))}
                        </div>
                        {getStatus('payment_exclusions') && <StatusMessage {...getStatus('payment_exclusions')!} className="mt-4" />}
                      </div>

                      <div className="space-y-3">
                        <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1 flex items-center gap-2">
                          <ShoppingBasket size={12} />
                          {t.shipping_exclusions_title || "Exclude Shipping Methods"}
                        </label>
                        <div className="grid grid-cols-1 gap-2 max-h-[300px] overflow-y-auto pr-2 no-scrollbar ">
                          {Object.keys(data.shippingMethods || {}).map(id => (
                            <label key={id} className={`flex items-center justify-between p-3 rounded-[5px] border transition-all cursor-pointer ${(settings.wawp_disable_otp_for_shipping_methods as string[] || []).includes(id)
                              ? 'border-emerald-500 bg-emerald-50/10' : 'border-slate-100 bg-white hover:border-slate-200'
                              }`}>
                              <span className="text-[13px] font-bold text-slate-700 truncate mr-2" title={(data.shippingMethods as Record<string, string>)[id]}>{(data.shippingMethods as Record<string, string>)[id]}</span>
                              <input
                                type="checkbox"
                                className="w-3.5 h-3.5 rounded border-slate-300 text-[#004449] focus:ring-[#004449]"
                                checked={(settings.wawp_disable_otp_for_shipping_methods as string[] || []).includes(id)}
                                onChange={(e) => {
                                  const current = settings.wawp_disable_otp_for_shipping_methods as string[] || [];
                                  const next = e.target.checked
                                    ? [...current, id]
                                    : current.filter((oldId: string) => oldId !== id);
                                  handleChange('wawp_disable_otp_for_shipping_methods', next);
                                }}
                              />
                            </label>
                          ))}
                        </div>
                        {getStatus('shipping_exclusions') && <StatusMessage {...getStatus('shipping_exclusions')!} className="mt-4" />}
                      </div>
                    </div>
                  </div>
                </SettingCard>

                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.core_sync_title || "WooCommerce Core Sync"}
                    description={t.core_sync_desc || "Synchronize these settings with your WooCommerce defaults."}
                    icon={Settings2}
                  />

                  <div className="p-6 md:p-8 grid grid-cols-1 lg:grid-cols-2 gap-4">
                    {[
                      { id: 'woocommerce_enable_guest_checkout', label: 'Guest Checkout', desc: 'Allow orders without accounts' },
                      { id: 'woocommerce_enable_checkout_login_reminder', label: 'Login Reminder', desc: 'Help returning customers' },
                      { id: 'woocommerce_enable_signup_and_login_from_checkout', label: 'Account Creation', desc: 'Build customer loyalty' },
                      { id: 'woocommerce_registration_generate_password', label: 'Password Setup', desc: 'Secure auto-generation' }
                    ].map(item => (
                      <div key={item.id} className="p-4 bg-slate-50/50 border border-slate-200 rounded-[5px] flex items-center justify-between group transition-all">
                        <div className="space-y-0.5">
                          <span className="block text-[13px] font-bold text-slate-900">{item.label}</span>
                          <span className="block text-[10px] text-slate-400 font-bold uppercase tracking-tight leading-none">{item.desc}</span>
                        </div>
                        <Switch
                          checked={settings[item.id] === 'yes'}
                          onCheckedChange={() => handleToggle(item.id)}
                        />
                      </div>
                    ))}
                  </div>
                </SettingCard>

              </div>
            )}

            {activeTab === 'style' && (
              <div className="space-y-6 animate-in slide-in-from-right-4 duration-500">
                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title={t.visual_custom_title || "Visual Customization"}
                    description={t.visual_custom_desc || "Ensure the verification popup matches your brand identity."}
                    icon={Palette}
                  />

                  <div className="p-6 md:p-8 space-y-10">
                    <section className="space-y-4">
                      <SettingInput
                        label="Popup Header Text"
                        value={settings.wawp_checkout_otp_title as string}
                        onChange={(val) => handleChange('wawp_checkout_otp_title', val)}
                        placeholder=""
                        icon={Type}
                        description='Title displayed at top of verification popup. Default: "Confirm your order"'
                        className="max-w-2xl"
                        showFormatting={true}
                        showEmoji={true}
                      />
                    </section>

                    <section className="space-y-4">
                      <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Branding Presets</label>
                      <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
                        {[
                          {
                            id: 'default', label: 'Default', colors: {
                              'wawp_checkout_otp_button_color': '#22c55e', 'wawp_checkout_otp_button_text_color': '#ffffff',
                              'wawp_checkout_otp_resend_color': '#64748b', 'wawp_checkout_otp_resend_text_color': '#ffffff',
                            }
                          },
                          {
                            id: 'wawp', label: 'Teal', colors: {
                              'wawp_checkout_otp_button_color': '#004449', 'wawp_checkout_otp_button_text_color': '#ffffff',
                              'wawp_checkout_otp_resend_color': '#cbd5e1', 'wawp_checkout_otp_resend_text_color': '#0f172a',
                            }
                          },
                          {
                            id: 'ocean', label: 'Ocean', colors: {
                              'wawp_checkout_otp_button_color': '#0891b2', 'wawp_checkout_otp_button_text_color': '#ffffff',
                              'wawp_checkout_otp_resend_color': '#e0f2fe', 'wawp_checkout_otp_resend_text_color': '#0369a1',
                            }
                          },
                          {
                            id: 'midnight', label: 'Midnight', colors: {
                              'wawp_checkout_otp_button_color': '#7c3aed', 'wawp_checkout_otp_button_text_color': '#ffffff',
                              'wawp_checkout_otp_resend_color': '#1e293b', 'wawp_checkout_otp_resend_text_color': '#ffffff',
                            }
                          },
                          {
                            id: 'sunset', label: 'Sunset', colors: {
                              'wawp_checkout_otp_button_color': '#ea580c', 'wawp_checkout_otp_button_text_color': '#ffffff',
                              'wawp_checkout_otp_resend_color': '#991b1b', 'wawp_checkout_otp_resend_text_color': '#ffffff',
                            }
                          },
                          {
                            id: 'minimal', label: 'Minimal', colors: {
                              'wawp_checkout_otp_button_color': '#171717', 'wawp_checkout_otp_button_text_color': '#ffffff',
                              'wawp_checkout_otp_resend_color': '#f5f5f5', 'wawp_checkout_otp_resend_text_color': '#404040',
                            }
                          },
                        ].map(preset => (
                          <button
                            key={preset.id}
                            onClick={() => {
                              setSettings((prev) => ({
                                ...prev,
                                wawp_checkout_color_theme: preset.id,
                                ...preset.colors
                              }));
                            }}
                            className={`p-3.5 rounded-xl border-2 transition-all text-center group relative overflow-hidden ${settings.wawp_checkout_color_theme === preset.id
                              ? 'border-[#004449] bg-white ring-4 ring-[#004449]/5'
                              : 'border-slate-100 bg-white hover:border-slate-200'
                              }`}
                          >
                            <div className="flex justify-center gap-1.5 mb-2.5">
                              {Array.from(new Set(Object.values(preset.colors))).slice(0, 3).map((c, i) => (
                                <div key={i} className="w-4 h-4 rounded-full border border-white shadow-sm" style={{ backgroundColor: c as string }} />
                              ))}
                            </div>
                            <span className={`text-[10px] font-black uppercase tracking-widest ${settings.wawp_checkout_color_theme === preset.id ? 'text-[#004449]' : 'text-slate-400'
                              }`}>{preset.label}</span>
                          </button>
                        ))}
                      </div>
                    </section>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-12 pt-8 border-t border-slate-50">
                      <div className="space-y-4">
                        <div className="flex items-center gap-2 px-1">
                          <div className="w-2 h-4 rounded-full bg-blue-500" />
                          <h4 className="text-[13px] font-black text-slate-800 uppercase tracking-tight">Verification Button</h4>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">Background</label>
                            <div className="flex gap-2">
                              <input type="color" value={settings.wawp_checkout_otp_button_color as string || '#22c55e'} onChange={(e) => handleChange('wawp_checkout_otp_button_color', e.target.value)} className="w-10 h-8 rounded-[5px] cursor-pointer border-2 border-white shadow-none" />
                              <input type="text" value={settings.wawp_checkout_otp_button_color as string || '#22c55e'} onChange={(e) => handleChange('wawp_checkout_otp_button_color', e.target.value)} className="flex-1 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold shadow-none" />
                            </div>
                          </div>
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">Text Color</label>
                            <div className="flex gap-2">
                              <input type="color" value={settings.wawp_checkout_otp_button_text_color as string || '#ffffff'} onChange={(e) => handleChange('wawp_checkout_otp_button_text_color', e.target.value)} className="w-10 h-8 rounded-[5px] cursor-pointer border-2 border-white shadow-none" />
                              <input type="text" value={settings.wawp_checkout_otp_button_text_color as string || '#ffffff'} onChange={(e) => handleChange('wawp_checkout_otp_button_text_color', e.target.value)} className="flex-1 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold shadow-none" />
                            </div>
                          </div>
                        </div>
                        <div className="mt-4 p-4 rounded-xl text-center font-black text-[13px] uppercase tracking-widest shadow-lg shadow-black/5" style={{ backgroundColor: settings.wawp_checkout_otp_button_color as string, color: settings.wawp_checkout_otp_button_text_color as string }}>
                          Confirm Order
                        </div>
                      </div>

                      <div className="space-y-4">
                        <div className="flex items-center gap-2 px-1">
                          <div className="w-2 h-4 rounded-full bg-slate-400" />
                          <h4 className="text-[13px] font-black text-slate-800 uppercase tracking-tight">Retry Logic Actions</h4>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">Background</label>
                            <div className="flex gap-2">
                              <input type="color" value={settings.wawp_checkout_otp_resend_color as string || '#64748b'} onChange={(e) => handleChange('wawp_checkout_otp_resend_color', e.target.value)} className="w-10 h-8 rounded-[5px] cursor-pointer border-2 border-white shadow-none" />
                              <input type="text" value={settings.wawp_checkout_otp_resend_color as string || '#64748b'} onChange={(e) => handleChange('wawp_checkout_otp_resend_color', e.target.value)} className="flex-1 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold shadow-none" />
                            </div>
                          </div>
                          <div className="space-y-1.5">
                            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest px-1">Text Color</label>
                            <div className="flex gap-2">
                              <input type="color" value={settings.wawp_checkout_otp_resend_text_color as string || '#ffffff'} onChange={(e) => handleChange('wawp_checkout_otp_resend_text_color', e.target.value)} className="w-10 h-8 rounded-[5px] cursor-pointer border-2 border-white shadow-none" />
                              <input type="text" value={settings.wawp_checkout_otp_resend_text_color as string || '#ffffff'} onChange={(e) => handleChange('wawp_checkout_otp_resend_text_color', e.target.value)} className="flex-1 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold shadow-none" />
                            </div>
                          </div>
                        </div>
                        <div className="mt-4 p-4 rounded-xl text-center font-black text-[13px] uppercase tracking-widest shadow-lg shadow-black/5" style={{ backgroundColor: settings.wawp_checkout_otp_resend_color as string, color: settings.wawp_checkout_otp_resend_text_color as string }}>
                          Resend Verification Code
                        </div>
                      </div>
                    </div>
                  </div>
                </SettingCard>
              </div>
            )}
          </motion.div>
        </AnimatePresence>
      </div>


      <PersonalizationDialog
        open={isPersonalizationOpen}
        onOpenChange={setIsPersonalizationOpen}
        onInsert={(value) => {
          handleChange(personalizationEditorId, (settings[personalizationEditorId] || '') + value);
          setIsPersonalizationOpen(false);
        }}
        placeholders={
          personalizationEditorId === 'wawp_otp_subject_email' ? {
            '{{otp}}': 'OTP Code',
            '{{name}}': 'First Name',
            '{{last}}': 'Last Name',
            '{{shop_name}}': 'Shop Name',
          } : {
            '{{otp}}': 'OTP Code',
            '{{name}}': 'First Name',
            '{{last}}': 'Last Name',
            '{{shop_name}}': 'Shop Name',
            '{{site_link}}': 'Website URL'
          }
        }
      />
    </div>
  </SettingsLayout>
  );
};



export default CheckoutVerificationSettings;
