import React, { useState, useMemo } from 'react';
import {
  Smartphone,
  Mail,
  Palette,
  Code2,
  Save,
  Trash2,
  Plus,
  ArrowRight,
  Image as ImageIcon,
  Settings as SettingsIcon,
  Key,
  Zap,
  Layout,
  MessageSquare,
  ShieldCheck,
  Settings2,
  Brackets,
  Clock,
  Link,
  Heading,
  ExternalLink,
  AlignLeft
} from 'lucide-react';
import { PersonalizationDialog } from './components/ui/personalization-dialog';
import {
  ModernCardHeader,
  SettingInput,
  StatusMessage,
  CodeEditor,
  IntegrationCard,
  ColorInput,
  FlatTabs,
  ShortcodeManager,
  SettingCard,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  HeaderSaveStatus,
  SettingsTabContent,
  MethodButton
} from './components/ui/settings-ui';
import { SearchableSelect } from './components/ui/searchable-select';
import { Switch } from './components/ui/switch';
import { Label } from './components/ui/label';
import { Badge } from './components/ui/badge';
import WhatsAppAuthSettings from './components/common/WhatsAppAuthSettings';
import { useSettingsManager, type ModuleData } from './hooks/use-settings-manager';

import type { DashboardData, PasswordlessLoginSettings as Settings, RedirectRule } from './types';

const PasswordlessLoginSettings: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = rootData?.passwordlessLoginSettings;
  const msgs = useMemo(() => rootData?.status_messages || {}, [rootData?.status_messages]);
  const [activeTab, setActiveTab] = useState('general');

  const {
    settings,
    updateSetting,
    handleSave,
    saveStatus,
    hasUnsavedChanges,
    isSaving,
    t
  } = useSettingsManager<Settings>({
    rootData,
    moduleData: data as unknown as ModuleData,
    initialSettings: {
      login_method: 'phone_login',
      session_lifetime_type: 'lifetime',
      session_lifetime_value: 0,
      primary_email_method: 'otp',
      enable_email_password: 0,
      enable_email: 1,
      otp_subject_email: '',
      otp_email_template_id: '',
      otp_message_email: '',
      primary_phone_method: 'whatsapp',
      enable_whatsapp: 1,
      otp_message_whatsapp: '',
      enable_firebase_sms: 0,
      redirect_rules: [],
      logo: '',
      title: '',
      description: '',
      color_theme: 'default',
      custom_css: '',
      custom_shortcode: []
    },
    onBeforeSave: (s) => ({
      ...s,
      custom_shortcode: Array.isArray(s.custom_shortcode) ? s.custom_shortcode : []
    })
  });

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

  const { availability, roles } = data || { availability: {}, roles: {} };

  if (!data || !settings) return null;


  const addRedirectRule = () => {
    const rules = [...(settings.redirect_rules || [])];
    rules.push({ role: 'all', redirect_url: '' });
    updateSetting('redirect_rules', rules);
  };

  const removeRedirectRule = (index: number) => {
    const rules = [...(settings.redirect_rules || [])];
    rules.splice(index, 1);
    updateSetting('redirect_rules', rules);
  };

  const updateRedirectRule = (index: number, field: keyof RedirectRule, value: string) => {
    const rules = [...(settings.redirect_rules || [])];
    rules[index] = { ...rules[index], [field]: value };
    updateSetting('redirect_rules', rules);
  };

  const handleLogoUpload = () => {
    interface WordPressWindow {
      wp?: {
        media: (args: Record<string, unknown>) => {
          on: (event: string, callback: () => void) => void;
          open: () => void;
          state: () => {
            get: (key: string) => {
              first: () => {
                toJSON: () => { url: string };
              };
            };
          };
        };
      };
    }
    const wpWindow = window as unknown as WordPressWindow;
    if (!wpWindow.wp || !wpWindow.wp.media) return;
    const frame = wpWindow.wp.media({
      title: 'Select Logo',
      button: { text: 'Use this logo' },
      multiple: false
    });
    frame.on('select', () => {
      const attachment = frame.state().get('selection').first().toJSON();
      updateSetting('logo', attachment.url);
    });
    frame.open();
  };

  const tabs = [
    { id: 'general', label: t.general || 'General', icon: SettingsIcon },
    { id: 'email-login', label: t.email_login || 'Email Login', icon: Mail },
    { id: 'phone-login', label: t.phone_login || 'Phone Login', icon: Smartphone },
    { id: 'redirection', label: t.redirection || 'Redirection', icon: ArrowRight },
    { id: 'style', label: t.style || 'Style', icon: Palette },
    { id: 'shortcodes', label: t.shortcodes || 'Shortcodes', icon: Code2 }
  ];

  return (
    <SettingsLayout>
      <SettingsHeader
        title={t.passwordless_login_title || "Passwordless Login"}
        description={t.passwordless_login_desc || "Configure passwordless authentication via WhatsApp, Email Magic Link, or Firebase SMS."}
      >
        <div className="flex items-center gap-3">
          <HeaderSaveStatus status={saveStatus === 'idle' && hasUnsavedChanges ? 'unsaved' : saveStatus} />

          <AdminButton
            onClick={() => handleSave()}
            loading={isSaving}
            icon={Save}
            className="px-8"
          >
            {isSaving ? 'Saving...' : 'Save Settings'}
          </AdminButton>
        </div>
      </SettingsHeader>

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

      {/* Tab Content */}
      <div className="space-y-6">
        <SettingsTabContent id="general" activeTab={activeTab}>
          {/* Default Login Method */}
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.default_login_method_title || "Default Login Method"}
              description={t.default_login_method_desc || "Choose the login method you’d like your users to see first on the login page."}
              icon={Layout}
            />              <div className="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 gap-4">
              {[
                { id: 'phone_login', label: t.phone_login_label || 'Phone Login', icon: Smartphone, description: t.phone_login_desc || 'Direct WhatsApp or SMS verification', color: 'text-indigo-600', bg: 'bg-indigo-50' },
                { id: 'email_login', label: t.email_login_label || 'Email Login', icon: Mail, description: t.email_login_desc || 'Secure OTP or password auth', color: 'text-blue-600', bg: 'bg-blue-50' }
              ].map(item => (
                <MethodButton
                  key={item.id}
                  active={settings.login_method === item.id}
                  label={item.label}
                  description={item.description}
                  icon={item.icon}
                  color={item.color}
                  bg={item.bg}
                  onClick={() => updateSetting('login_method', item.id)}
                />
              ))}
            </div>
            <div className="px-6 md:px-8 pb-6 md:pb-8">
              <StatusMessage
                type="active"
                message={settings.login_method === 'phone_login' 
                  ? "Users will see the <b>WhatsApp/Phone</b> login field by default. Highly recommended for mobile-first audiences." 
                  : "Users will see the <b>Email</b> login field first. Best for professional or desktop-heavy platforms."}
              />
            </div>
          </SettingCard>

          {/* Security & Session */}
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.security_session_title || "Security & Session"}
              description={t.security_session_desc || "Manage session lifetime and other security protocols for authenticated users."}
              icon={ShieldCheck}
            />

            <div className="p-6 md:p-8">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div className="space-y-4">
                  <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Session Lifetime Type</Label>
                  <SearchableSelect
                    options={[
                      { value: "lifetime", label: "Lifetime (Follow WordPress)" },
                      { value: "minutes", label: "Minutes" },
                      { value: "hours", label: "Hours" },
                      { value: "days", label: "Days" }
                    ]}
                    value={settings.session_lifetime_type}
                    onChange={(val) => updateSetting('session_lifetime_type', 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]"
                  />
                </div>

                {settings.session_lifetime_type !== 'lifetime' && (
                  <div className="space-y-4">
                    <SettingInput
                      label="Lifetime Value"
                      type="number"
                      value={settings.session_lifetime_value?.toString() || '0'}
                      onChange={(val: string) => updateSetting('session_lifetime_value', parseInt(val) || 0)}
                      icon={Clock}
                      placeholder=""
                      description={settings.session_lifetime_type === 'lifetime' ? undefined : settings.session_lifetime_type}
                    />
                  </div>
                )}
              </div>
              <div className="mt-6">
                <StatusMessage
                  type={settings.session_lifetime_type === 'lifetime' ? 'active' : 'warning'}
                  message={settings.session_lifetime_type === 'lifetime' 
                    ? "Sessions will follow your global WordPress login duration (usually 14 days)." 
                    : `User sessions will expire automatically after <b>${settings.session_lifetime_value} ${settings.session_lifetime_type}</b> of inactivity.`}
                />
              </div>
            </div>
          </SettingCard>
        </SettingsTabContent>

        <SettingsTabContent id="email-login" activeTab={activeTab}>
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.primary_email_method_title || "Primary Email Method"}
              description={t.primary_email_method_desc || "Decide which login flow takes precedence when a user provides their email address."}
              icon={Mail}
            />

            <div className="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 gap-4">
              {[
                { id: 'otp', label: t.email_magic_link_title || 'Email Magic Link Login', icon: Mail, description: t.email_magic_link_desc || 'Users receive a secure link in their inbox to authorize login instantly.', color: 'text-emerald-600', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg", bg: 'bg-emerald-50' },
                { id: 'password', label: t.password_label || 'Classic Password', icon: Key, description: t.password_desc || 'Standard site credentials', color: 'text-amber-600', bg: 'bg-amber-50' }
              ].map(item => (
                <MethodButton
                  key={item.id}
                  active={settings.primary_email_method === item.id}
                  label={item.label}
                  description={item.description}
                  icon={item.icon}
                  iconPath={item.iconPath}
                  color={item.color}
                  bg={item.bg}
                  onClick={() => updateSetting('primary_email_method', item.id)}
                />
              ))}
            </div>
          </SettingCard>

          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.enable_email_password_title || "Enable Email & Password"}
              description={t.enable_email_password_desc || "Allow users to login using their standard WordPress credentials."}
              icon={ShieldCheck}
              rightAction={
                <Switch
                  checked={settings.enable_email_password == 1}
                  onCheckedChange={(checked) => updateSetting('enable_email_password', checked ? 1 : 0)}
                />
              }
            />
          </SettingCard>

          <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."}
              icon={Mail}
              rightAction={
                <Switch
                  checked={settings.enable_email == 1}
                  onCheckedChange={(checked) => updateSetting('enable_email', checked ? 1 : 0)}
                />
              }
            />

            <div className="p-6 md:p-8 space-y-6">
              <div className="space-y-4">
                <div className="flex items-center gap-2 mb-2 pl-1">
                  <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.otp_subject_email || ''}
                  onChange={(val: string) => updateSetting('otp_subject_email', val)}
                  placeholder=""
                  icon={Mail}
                  button={
                    <button
                      className="p-2 text-slate-400 hover:text-blue-600 transition-colors"
                      onClick={() => {
                        setPersonalizationEditorId('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">
                      <SearchableSelect
                        options={(data as { emailTemplates?: Array<{ id: string | number, name: string }> })?.emailTemplates?.map((tpl) => ({
                          value: tpl.id.toString(),
                          label: tpl.name
                        })) || (rootData?.registrationForm as { emailTemplates?: Array<{ id: string | number, name: string }> })?.emailTemplates?.map((tpl) => ({
                          value: tpl.id.toString(),
                          label: tpl.name
                        })) || []}
                        value={settings.otp_email_template_id?.toString() || ""}
                        onChange={(val) => updateSetting('otp_email_template_id', val)}
                        placeholder="Select Email Template..."
                        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]"
                      />
                    </div>
                    <a
                      href="/wp-admin/admin.php?page=wawp&wawp_section=email_templates"
                      className="px-4 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>

              <StatusMessage
                type={settings.enable_email == 1 && (availability.email_otp?.available) ? 'active' : (settings.enable_email == 1 ? 'error' : 'inactive')}
                message={settings.enable_email == 1 && (availability.email_otp?.available) ? msgs.login_em_active : (settings.enable_email == 1 ? "Attention: Email OTP functionality might be limited by your server mail configuration." : msgs.login_em_inactive)}
              />
            </div>
          </SettingCard>
        </SettingsTabContent>

        <SettingsTabContent id="phone-login" activeTab={activeTab}>
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.primary_phone_method_title || "Primary Phone Method"}
              description={t.primary_phone_method_desc || "Choose the preferred channel for delivering verification codes to mobile devices."}
              icon={Smartphone}
            />

            <div className="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 gap-4">
              {[
                { id: 'whatsapp', label: t.whatsapp_label || 'WhatsApp Web Authentication', icon: MessageSquare, description: t.whatsapp_desc || 'High-speed WhatsApp OTP & Interactive verification via your own WhatsApp instances.', color: 'text-emerald-600', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", bg: 'bg-emerald-50' },
                { id: 'firebase', label: t.firebase_label || 'Firebase SMS Authentication', icon: Zap, description: t.firebase_desc || 'Use Google Firebase to send SMS verification codes globally (Requires API Key).', color: 'text-orange-600', iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg", bg: 'bg-orange-50' }
              ].map(item => (
                <MethodButton
                  key={item.id}
                  active={settings.primary_phone_method === item.id}
                  label={item.label}
                  description={item.description}
                  icon={item.icon}
                  iconPath={item.iconPath}
                  color={item.color}
                  bg={item.bg}
                  onClick={() => updateSetting('primary_phone_method', item.id)}
                />
              ))}
            </div>
          </SettingCard>

          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.whatsapp_web_auth_title || "WhatsApp Web Authentication"}
              description={t.whatsapp_web_auth_desc || "High-speed WhatsApp OTP & Interactive verification via your own WhatsApp instances."}
              icon={() => <img src={(rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg"} className="w-5 h-5 object-contain opacity-80" alt="" />}
              rightAction={
                <Switch
                  checked={settings.enable_whatsapp == 1}
                  onCheckedChange={(checked) => updateSetting('enable_whatsapp', checked ? 1 : 0)}
                />
              }
            />

            <div className="p-6 md:p-8 space-y-6">


              <div className="space-y-6 pt-4 border-t border-slate-100">
                <WhatsAppAuthSettings
                  settings={settings as unknown as Record<string, string | number | boolean>}
                  updateSetting={updateSetting}
                  availability={availability}
                  optionNames={{
                    whatsappAuthType: 'whatsapp_auth_type',
                    whatsappOtpLangType: 'whatsapp_otp_lang_type',
                    whatsappOtpCustomLang: 'whatsapp_otp_custom_lang',
                    whatsappOtpFooterEnabled: 'whatsapp_otp_footer_enabled',
                    whatsappOtpFooter: 'whatsapp_otp_footer',
                    whatsappListTitle: 'whatsapp_list_title',
                    whatsappListDesc: 'whatsapp_list_desc',
                    whatsappListItem1: 'whatsapp_list_item1',
                    whatsappListItem1Desc: 'whatsapp_list_item1_desc',
                    whatsappListItem2: 'whatsapp_list_item2',
                    whatsappListItem2Desc: 'whatsapp_list_item2_desc',
                    whatsappListButton: 'whatsapp_list_button',
                    whatsappListFooter: 'whatsapp_list_footer'
                  }}
                  msgs={msgs}
                />
              </div>

              <StatusMessage
                type={settings.enable_whatsapp == 1 && (availability.whatsapp?.available) ? 'active' : (settings.enable_whatsapp == 1 ? 'error' : 'inactive')}
                message={settings.enable_whatsapp == 1 && (availability.whatsapp?.available) ? msgs.login_wa_active : (settings.enable_whatsapp == 1 ? "Error: Internal WhatsApp engine is disconnected." : msgs.login_wa_inactive)}
              />
            </div>
          </SettingCard>

          <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)."}
              icon={() => <img src={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"} className="w-5 h-5 object-contain opacity-80" alt="" />}
              rightAction={
                <Switch
                  checked={settings.enable_firebase_sms == 1}
                  onCheckedChange={(checked) => updateSetting('enable_firebase_sms', checked ? 1 : 0)}
                />
              }
            />
            <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={(availability.firebase?.available) && settings.enable_firebase_sms == 1 ? 'active' : (settings.enable_firebase_sms == 1 ? 'error' : 'inactive')}
                message={(availability.firebase?.available) && settings.enable_firebase_sms == 1 ? "Firebase Account found. System is ready to route messages through Google gateway." : (settings.enable_firebase_sms == 1 ? "Error: Firebase configuration is missing or invalid." : msgs.login_fb_inactive)}
              />
            </div>
          </SettingCard>
        </SettingsTabContent>

        <SettingsTabContent id="redirection" activeTab={activeTab}>
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              title={t.redirection_rules_title || "Post-Login Redirection"}
              description={t.redirection_rules_desc || "Define exactly where each user group lands after a successful authentication event."}
              icon={ArrowRight}
              rightAction={
                <AdminButton
                  onClick={addRedirectRule}
                  icon={Plus}
                >
                  Add New Rule
                </AdminButton>
              }
            />

            <div className="p-6 md:p-8 space-y-4">
              {(settings.redirect_rules || []).map((rule: RedirectRule, index: number) => (
                <div key={index} className="grid grid-cols-1 md:grid-cols-12 gap-5 p-6 bg-slate-50/50 border border-slate-100 rounded-[5px] group animate-in slide-in-from-right-4 duration-300 relative transition-all hover:bg-white hover:border-slate-200">
                  <div className="md:col-span-4 space-y-2">
                    <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Target User Role</Label>
                    <SearchableSelect
                      options={[
                        { value: "all", label: "Everywhere (Global)" },
                        ...Object.entries(roles).map(([val, role]) => ({
                          value: val,
                          label: (role as { name: string }).name
                        }))
                      ]}
                      value={rule.role}
                      onChange={(val) => updateRedirectRule(index, 'role', val)}
                      className="h-11 bg-white border-slate-200 text-slate-700 font-bold text-[13px] hover:border-[#004449]/30 transition-all rounded-[5px]"
                    />
                  </div>
                  <div className="md:col-span-7">
                    <SettingInput
                      label="Redirection Endpoint"
                      value={rule.redirect_url}
                      onChange={(val: string) => updateRedirectRule(index, 'redirect_url', val)}
                      placeholder=""
                      icon={Link}
                      labelHidden
                    />
                  </div>
                  <div className="md:col-span-1 flex items-end justify-center pb-1">
                    <button
                      onClick={() => removeRedirectRule(index)}
                      className="w-11 rounded-lg flex items-center justify-center text-rose-400 hover:text-rose-600 hover:bg-rose-50 transition-all active:scale-90"
                    >
                      <Trash2 size={20} />
                    </button>
                  </div>
                </div>
              ))}

              {(settings.redirect_rules || []).length === 0 && (
                <div className="py-20 text-center bg-slate-50/20 border-2 border-dashed border-slate-100 rounded-[5px]">
                  <div className="h-16 w-16 rounded-xl bg-white border border-slate-100 flex items-center justify-center mx-auto mb-4 text-slate-200 ">
                    <ArrowRight size={32} />
                  </div>
                  <h3 className="text-slate-900 font-black uppercase tracking-tight mb-1">No custom endpoints defined</h3>
                  <p className="text-slate-400 text-[13px] font-medium max-w-xs mx-auto">Users will follow the default WordPress landing page after login.</p>
                </div>
              )}

              <StatusMessage
                type={(settings.redirect_rules || []).length > 0 ? 'active' : 'inactive'}
                message={(settings.redirect_rules || []).length > 0 ? msgs.login_redir_active : msgs.login_redir_inactive}
              />
            </div>
          </SettingCard>
        </SettingsTabContent>

        <SettingsTabContent id="style" activeTab={activeTab}>
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader 
              title={t.visual_exp_title || "Visual Experience"} 
              description={t.visual_exp_desc || "Customize the look and feel of the login form to match your brand identity."} 
              icon={Palette} 
            />

            <div className="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 gap-12">
              <div className="space-y-8">
                <div className="space-y-4">
                  <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Form Logo</Label>
                  <div className="flex items-center gap-6">
                    <div className="h-32 w-32 rounded-[5px] bg-slate-50 border-2 border-dashed border-slate-200 flex items-center justify-center relative overflow-hidden group transition-all hover:bg-slate-100">
                      {settings.logo ? (
                        <>
                          <img src={settings.logo} className="h-full w-full object-contain p-4 transition-transform group-hover:scale-110" />
                          <div className="absolute inset-0 bg-slate-900/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2 backdrop-blur-[2px]">
                            <button onClick={handleLogoUpload} className="h-8 w-8 bg-white rounded-lg flex items-center justify-center text-slate-700 hover:text-[#004449]"><ImageIcon size={16} /></button>
                            <button onClick={() => updateSetting('logo', '')} className="h-8 w-8 bg-white rounded-lg flex items-center justify-center text-rose-500 hover:text-rose-700"><Trash2 size={16} /></button>
                          </div>
                        </>
                      ) : (
                        <div className="text-center cursor-pointer" onClick={handleLogoUpload}>
                          <ImageIcon className="mx-auto text-slate-200 mb-2" size={32} />
                          <span className="text-[9px] font-black uppercase text-slate-400 tracking-tighter">Upload</span>
                        </div>
                      )}
                    </div>
                    <div className="flex-1 space-y-3">
                      <p className="text-[11px] text-slate-400 font-medium leading-relaxed">Better to use a horizontal PNG/SVG with transparent background.</p>
                      <button onClick={handleLogoUpload} className="px-4 py-2 bg-white border border-slate-200 text-slate-700 text-[11px] font-black uppercase tracking-widest rounded-[5px] hover:border-[#004449] hover:text-[#004449] transition-all">Select Image</button>
                    </div>
                  </div>
                  <div className="mt-4">
                    <StatusMessage
                      type={settings.logo ? 'active' : 'inactive'}
                      message={settings.logo ? "Your brand logo will appear at the top of the login form." : "No logo set. The form will display your site title instead."}
                    />
                  </div>
                </div>

                <SettingInput label="Form Headline" value={settings.title} onChange={(val: string) => updateSetting('title', val)} icon={Heading} placeholder="" />
                <SettingInput
                  label="Form Description"
                  value={settings.description}
                  onChange={(val: string) => updateSetting('description', val)}
                  icon={AlignLeft}
                  placeholder=""
                  showEmoji
                  showFormatting
                />
                <StatusMessage
                  type={(settings.title || settings.description) ? 'active' : 'inactive'}
                  message={(settings.title || settings.description) ? "Custom form header (title and description) is active and visible to users." : "Using default header text. Consider adding a custom title to welcome users."}
                />
              </div>

              <div className="space-y-8">
                <div className="space-y-4">
                  <Label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Theme Presets</Label>
                  <div className="grid grid-cols-3 gap-3">
                    {data?.colorPresets && Object.entries(data.colorPresets).map(([id, p]) => (
                      <button
                        key={id}
                        onClick={() => {
                          updateSetting('color_theme', id);
                          if (p.colors) {
                            Object.entries(p.colors).forEach(([k, v]) => updateSetting(k, v));
                          }
                        }}
                        className={`flex flex-col items-center gap-2 p-3 rounded-[5px] border-2 transition-all ${settings.color_theme === id ? 'border-[#004449] bg-[#004449]/5' : 'bg-slate-50/50 border-slate-100 hover:border-slate-300'}`}
                      >
                        <div className="h-6 w-6 rounded-full border-2 border-white " style={{ backgroundColor: p.colors?.whatsapp_button_color || '#ddd' }} />
                        <span className={`text-[10px] font-black uppercase tracking-tight ${settings.color_theme === id ? 'text-[#004449]' : 'text-slate-400'}`}>{p.name || id}</span>
                      </button>
                    ))}
                  </div>
                </div>

                <div className="space-y-6">
                  <div className="flex items-center justify-between pb-2 border-b border-slate-100">
                    <h4 className="text-[11px] font-black uppercase text-slate-900 tracking-widest">Global Accent Colors</h4>
                  </div>
                  <div className="grid grid-cols-2 gap-6 max-h-[350px] overflow-y-auto pr-2 no-scrollbar">
                    <ColorInput label="WA Button" value={settings.whatsapp_button_color || ''} onChange={(val: string) => updateSetting('whatsapp_button_color', val)} />
                    <ColorInput label="Firebase Button" value={settings.firebase_button_color || ''} onChange={(val: string) => updateSetting('firebase_button_color', val)} />
                    <ColorInput label="Email Button" value={settings.email_otp_button_color || ''} onChange={(val: string) => updateSetting('email_otp_button_color', val)} />
                    <ColorInput label="Password Login" value={settings.password_login_button_color || ''} onChange={(val: string) => updateSetting('password_login_button_color', val)} />
                    <ColorInput label="Verify Action" value={settings.verify_button_color || ''} onChange={(val: string) => updateSetting('verify_button_color', val)} />
                    <ColorInput label="Resend Button" value={settings.resend_button_color || ''} onChange={(val: string) => updateSetting('resend_button_color', val)} />
                    <ColorInput label="Show Password" value={settings.show_password_button_color || ''} onChange={(val: string) => updateSetting('show_password_button_color', val)} />
                    <ColorInput label="Back Link" value={settings.back_button_color || ''} onChange={(val: string) => updateSetting('back_button_color', val)} />
                  </div>
                </div>
              </div>
            </div>

            <div className="mt-12 space-y-8 pt-8 border-t border-slate-100">
              <CodeEditor
                label="Custom Styling (CSS)"
                value={settings.custom_css}
                onChange={(val) => updateSetting('custom_css', val)}
                placeholder=".wawp-login-wrapper { background: #f9f9f9; }"
              />
              <StatusMessage
                type={settings.enable_premium_design == 1 ? 'active' : 'inactive'}
                message={settings.enable_premium_design == 1 ? "Premium custom design is active and applied to your login form." : "Standard design is active. Enable premium design to apply these custom styles."}
              />
            </div>
          </SettingCard>
        </SettingsTabContent>

        <SettingsTabContent id="shortcodes" activeTab={activeTab}>
          <div className="space-y-8 pb-12">
            <ShortcodeManager
              shortcodes={settings.custom_shortcode || []}
              onChange={(sc) => updateSetting('custom_shortcode', sc)}
              title={t.appended_content_title || "Appended Content"}
              description={t.appended_content_desc || "Add additional shortcodes to display dynamic content or banners below the core login form."}
              placeholder="[custom_shortcode]"
            />

            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <IntegrationCard
                title="Core Login Shortcode"
                description="Default method to render the Secure Passwordless Login form on any WordPress page."
                code="[wawp_otp_login]"
                badge="Production"
                badgeColor="brand"
                icon={ShieldCheck}
              />
              <IntegrationCard
                title="Developer Integration"
                description="Seamlessly embed the login logic directly within your custom theme template files."
                code={'<?php echo do_shortcode("[wawp_otp_login]"); ?>'}
                badge="PHP"
                badgeColor="brand"
                icon={Settings2}
                variant="brand"
              />
            </div>
          </div>
        </SettingsTabContent>

      </div>
      <PersonalizationDialog
        open={isPersonalizationOpen}
        onOpenChange={setIsPersonalizationOpen}
        onInsert={(value) => {
          if (personalizationEditorId) {
            updateSetting(personalizationEditorId, ((settings as Record<string, unknown>)[personalizationEditorId] as string || '') + value);
          }
          setIsPersonalizationOpen(false);
        }}
        placeholders={
          personalizationEditorId === 'otp_subject_email' ? {
            '{{otp}}': 'OTP Code',
            '{{user_name}}': 'Username',
            '{{shop_name}}': 'Shop Name',
          } : {
            '{{otp}}': 'OTP Code',
            '{{user_first_last_name}}': 'Full Name',
            '{{shop_name}}': 'Shop Name',
            '{{site_link}}': 'Website URL'
          }
        }
      />
    </SettingsLayout>
  );
};

export default PasswordlessLoginSettings;
