import React, { useState } from 'react';
import type { DashboardData } from './types';
import {
  ShoppingBasket,
  Settings2,
  Palette,
  Save,
  ShieldCheck,
  Brackets,
  Globe,
  MessageSquare,
  Mail,
  Flame,
  ExternalLink,
  Lock
} from 'lucide-react';
import { motion, AnimatePresence } from "framer-motion";
import { cn } from './lib/utils';
import { Switch } from './components/ui/switch';
import { Label } from './components/ui/label';
import { PersonalizationDialog } from './components/ui/personalization-dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './components/ui/select';
import { Badge } from './components/ui/badge';
import WhatsAppAuthSettings from './components/common/WhatsAppAuthSettings';
import {
  SettingCard,
  FlatTabs,
  ModernCardHeader,
  StatusMessage,
  SettingInput,
  SettingsLayout,
  SettingsHeader,
  PrimaryButton,
  HeaderSaveStatus,
  AdvancedAuthSettingsCards
} from './components/ui/settings-ui';

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

const CheckoutVerificationSettings: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = React.useMemo(() => rootData?.checkoutVerificationSettings || {
    options: {},
    paymentGateways: [],
    shippingMethods: {},
    instances: [],
    i18n: {},
    optionNames: {}
  }, [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 tabs = [
    { id: 'general', label: 'General Settings', icon: ShoppingBasket },
    { id: 'advanced', label: 'Advanced Logic', icon: Settings2 },
    { id: 'style', label: 'Visual Design', icon: Palette }
  ];

  return (
    <SettingsLayout>
      <SettingsHeader
        title="Checkout Verification"
        description="Verify customers WhatsApp at checkout to prevent fraud & fake orders."
      >
        <div className="flex items-center gap-3">
          <HeaderSaveStatus status={saveStatus === 'idle' && hasUnsavedChanges ? 'unsaved' : saveStatus} />

          <PrimaryButton
            onClick={() => handleSave(false)}
            loading={isSaving}
            icon={Save}
            className="h-10 px-10"
          >
            {isSaving ? 'Applying...' : 'Save Settings'}
          </PrimaryButton>
        </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="Checkout OTP Strategy"
                    description="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', icon: MessageSquare, description: 'Ultra-fast delivery via WAWP engine', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", color: 'text-emerald-600', bg: 'bg-emerald-50', border: 'border-emerald-100' },
                          { id: 'email', label: 'Email OTP', icon: Mail, description: 'Secure verification code', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg", color: 'text-blue-600', bg: 'bg-blue-50', border: 'border-blue-100' },
                          { id: 'firebase', label: 'Firebase SMS', icon: Flame, description: 'Reliable Google infrastructure', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg", color: 'text-orange-600', bg: 'bg-orange-50', border: 'border-orange-100' }
                        ].map(item => (
                          <div key={item.id} className="relative group">
                            <label className={cn(
                              "flex items-center gap-3 p-3 rounded-xl border-2 transition-all cursor-pointer relative overflow-hidden",
                              settings.wawp_checkout_otp_method === item.id
                                ? "bg-white border-[#004449] ring-4 ring-[#004449]/5"
                                : "bg-white border-slate-100 hover:border-slate-200"
                            )}>
                              <input
                                type="radio"
                                className="sr-only"
                                value={item.id}
                                checked={settings.wawp_checkout_otp_method === item.id}
                                onChange={() => handleChange('wawp_checkout_otp_method', item.id)}
                              />
                              <div className={cn(
                                "w-10 h-10 rounded-lg flex items-center justify-center transition-all border duration-300 shrink-0",
                                settings.wawp_checkout_otp_method === item.id ? `${item.bg} ${item.border}` : "bg-slate-50 border-slate-100"
                              )}>
                                {item.iconPath ? (
                                  <img src={item.iconPath} className="w-5 h-5 object-contain" alt="" />
                                ) : (
                                  <item.icon size={18} className={cn("transition-colors", settings.wawp_checkout_otp_method === item.id ? item.color : "text-slate-400")} />
                                )}
                              </div>
                              <div className="flex-1 min-w-0 flex flex-col justify-center">
                                <h4 className="text-[14px] font-bold tracking-tight !m-0 !p-0 leading-tight text-slate-900">{item.label}</h4>
                                <p className="text-[11px] font-medium text-slate-500 truncate !m-0 !p-0 leading-tight">{item.description}</p>
                              </div>
                              {settings.wawp_checkout_otp_method === item.id && (
                                <div className="w-5 h-5 rounded-full bg-[#004449] border-2 border-[#004449] text-white flex items-center justify-center transition-all shrink-0">
                                  <ShieldCheck size={12} strokeWidth={3} />
                                </div>
                              )}
                            </label>
                          </div>
                        ))}
                      </div>
                    </div>

                    <div className="space-y-2 pt-4 border-t border-slate-50">
                      <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">WhatsApp Instance Allocation</label>
                      <select
                        value={settings.wawp_selected_instance as string}
                        onChange={(e) => handleChange('wawp_selected_instance', e.target.value)}
                        className="w-full h-11 px-4 bg-slate-50/50 border border-slate-200 rounded-[5px] focus:border-[#004449] focus:bg-white outline-none transition-all text-sm font-bold shadow-none"
                      >
                        <option value="">-- Select Managed Instance --</option>
                        {(data.instances as Array<{ instance_id: string, name: string }>)?.map(inst => (
                          <option key={inst.instance_id} value={inst.instance_id}>{inst.name}</option>
                        ))}
                      </select>
                    </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">
                      <ModernCardHeader
                        title="WhatsApp Authentication"
                        description="Ultra-fast delivery via WAWP engine. Recommended for best conversion."
                        iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg"}
                      />

                      <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="Email Verification"
                        description="Secure verification code delivered directly to user inbox."
                        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..."
                          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">
                          <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Body Template</Label>
                          <div className="flex gap-2">
                            <div className="flex-1">
                              <Select
                                value={settings.wawp_otp_email_template_id?.toString() || ""}
                                onValueChange={(val) => handleChange('wawp_otp_email_template_id', val)}
                              >
                                <SelectTrigger className="h-11 bg-slate-50/50 border-slate-200 rounded-[5px] focus:border-[#004449] focus:bg-white transition-all font-bold text-slate-700 shadow-none outline-none">
                                  <SelectValue placeholder="Select Email Template..." />
                                </SelectTrigger>
                                <SelectContent>
                                  {(data as unknown as { emailTemplates: Array<{ id: number, name: string }> }).emailTemplates?.map(tpl => (
                                    <SelectItem key={tpl.id} value={tpl.id.toString()} className="text-[13px]">
                                      {tpl.name}
                                    </SelectItem>
                                  )) || (rootData?.registrationForm as unknown as { emailTemplates: Array<{ id: number, name: string }> })?.emailTemplates?.map(tpl => (
                                    <SelectItem key={tpl.id} value={tpl.id.toString()} className="text-[13px]">
                                      {tpl.name}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </div>
                            <a
                              href="/wp-admin/admin.php?page=wawp&wawp_section=email_templates"
                              className="px-4 h-11 border border-slate-200 bg-slate-50/30 hover:bg-slate-100 text-slate-500 rounded-[5px] flex items-center justify-center transition-all shadow-none"
                              title="Manage Templates"
                            >
                              <Settings2 size={16} />
                            </a>
                          </div>
                        </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="Firebase SMS Login"
                        description="Standard mobile SMS verification using Google's reliable Firebase infrastructure."
                        iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"}
                      />
                      <div className="p-6 md:p-8 space-y-4">
                        <div className="p-6 bg-orange-50/30 border border-orange-100 rounded-[5px] flex flex-col md:flex-row items-center gap-6">
                          <div className="h-12 w-12 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="grow text-center md:text-left">
                            <h4 className="text-[14px] font-bold text-orange-900">Firebase Console</h4>
                            <p className="text-[12px] text-orange-800/70 mt-0.5">SMS templates are managed securely within your Firebase dashboard.</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">
                            Open Console <ExternalLink size={14} className="!text-white" />
                          </a>
                        </div>
                      </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="Security Hardening"
                    description="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">Target Audience Profile</label>
                      <select
                        value={settings.wawp_otp_mode as string}
                        onChange={(e) => handleChange('wawp_otp_mode', e.target.value)}
                        className="w-full h-11 px-4 bg-slate-50/50 border border-slate-200 rounded-[5px] outline-none focus:border-[#004449] focus:bg-white transition-all text-sm font-bold shadow-none"
                      >
                        <option value="enable_for_all">Verify all customers (Recommended)</option>
                        <option value="enable_for_guests">Verify guests only</option>
                        <option value="enable_for_loggedin">Verify logged-in users only</option>
                      </select>
                      <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} />
                          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>
                      </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} />
                          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>
                      </div>
                    </div>
                  </div>
                </SettingCard>

                <SettingCard className="p-0 overflow-hidden">
                  <ModernCardHeader
                    title="WooCommerce Core Sync"
                    description="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>

                <AdvancedAuthSettingsCards
                  settings={settings}
                  updateSetting={handleChange}
                  keys={{
                    initialCooldown: 'initialCooldown',
                    maxCooldown: 'maxCooldown',
                    pollingInterval: 'pollingInterval',
                    progressBridge: 'progressBridge',
                    progressAlmost: 'progressAlmost',
                    progressGo: 'progressGo',
                    emailDomains: 'emailDomains'
                  }}
                />
              </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="Visual Customization"
                    description="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="Confirm your order"
                        description='Title displayed at top of verification popup. Default: "Confirm your order"'
                        className="max-w-2xl"
                      />
                    </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-10 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 h-10 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold" />
                            </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-10 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 h-10 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold" />
                            </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-10 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 h-10 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold" />
                            </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-10 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 h-10 px-3 bg-slate-50 border border-slate-200 rounded-[5px] text-xs font-mono font-bold" />
                            </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'
          }
        }
      />
    </SettingsLayout>
  );
};



export default CheckoutVerificationSettings;
