import { useState, useCallback, useEffect } from 'react';
import type { DashboardData } from './types';
import { SMTP_PRESETS } from './data/smtp-presets';
import { Label } from './components/ui/label';
import { Switch } from './components/ui/switch';
import {
  RefreshCw,
  Send,
  Zap,
  Plus,
  Trash2,
  CheckCircle2,
  Settings2,
  ChevronRight,
  Clock as ClockIcon,
  Globe,
  Mail,
  ArrowRight,
  ArrowLeft,
  ShieldCheck,
  Tag,
  Hash,
  User,
  Lock,
  UserCircle,
  X
} from 'lucide-react';
import { SearchableSelect } from './components/ui/searchable-select';
import {
  SettingsLayout,
  SettingsHeader,
  ModernCardHeader,
  SettingCard,
  AdminButton,
  SecondaryButton,
  GhostButton,
  SettingInput,
  MethodButton,
  StatusMessage,
  SaveWithStatus
} from './components/ui/settings-ui';
import { useSettingsSave } from './hooks/useSettingsSave';
import { Sheet, SheetContent } from './components/ui/sheet';






interface SMTPSettings {
  provider: string;
  host?: string;
  port?: number;
  encryption?: string;
  user?: string;
  pass?: string;
  from_email?: string;
  from_name?: string;
  auth?: number;
  api_key?: string;
  domain?: string;
  region?: string;
  access_key?: string;
  secret_key?: string;
}

interface SMTPAccount {
  id: number;
  account_name: string;
  provider: string;
  is_active: boolean;
  validated: boolean;
  config: SMTPSettings;
}

export default function SMTPSender({ data: dashboardData }: { data: DashboardData }) {
  const PROVIDERS = [
    { id: 'wp', name: 'WordPress', iconPath: `${dashboardData?.global?.pluginUrl}assets/icons/wordpress.svg`, desc: 'Default PHPMailer' },
    { id: 'smtp', name: 'Custom SMTP', iconPath: `${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`, desc: 'Any Mail Server' },
  ];

  const [accounts, setAccounts] = useState<SMTPAccount[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [currentStep, setCurrentStep] = useState(1);

  const [accountName, setAccountName] = useState('');
  const [isUserEditedName, setIsUserEditedName] = useState(false);

  const [settings, setSettings] = useState<SMTPSettings>({
    provider: 'smtp',
    host: '',
    port: 587,
    encryption: 'tls',
    user: '',
    pass: '',
    from_email: '',
    from_name: '',
    auth: 1,
    api_key: '',
    domain: '',
    region: 'us',
    access_key: '',
    secret_key: ''
  });

  const [statusMessage, setStatusMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);
  const [isTestingConnect, setIsTestingConnect] = useState(false);
  const [isTestingSend, setIsTestingSend] = useState(false);
  const [testEmail, setTestEmail] = useState('');
  const [presetSearch, setPresetSearch] = useState('');

  const { saveStatus, hasUnsavedChanges, isSaving, handleSave, markDirty } = useSettingsSave({
    onSave: async () => {
      try {
        const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': dashboardData.global.wpRestNonce
          },
          body: JSON.stringify({
            account_name: accountName,
            config: settings,
            id: editingId
          })
        });

        const result = await response.json();
        if (result.success) {
          window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'smtp-sender' } }));
          return true;
        }
        return false;
      } catch {
        return false;
      }
    }
  });

  // Before unload warning
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (hasUnsavedChanges && isDialogOpen) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges, isDialogOpen]);

  const fetchAccounts = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp${dashboardData.global.apiRestUrl.includes('?') ? '&' : '?'}_=${Date.now()}`, {
        method: 'GET',
        headers: {
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      });
      const result = await response.json();
      if (result.success) {
        setAccounts(result.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch SMTP accounts:', error);
    }
    setIsLoading(false);
  }, [dashboardData.global.apiRestUrl, dashboardData.global.wpRestNonce]);

  const [prevData, setPrevData] = useState(dashboardData);
  if (dashboardData !== prevData) {
    setPrevData(dashboardData);
    fetchAccounts();
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      fetchAccounts();
    }, 0);
    return () => clearTimeout(timer);
  }, [fetchAccounts]);


  const handleInputChange = <K extends keyof SMTPSettings>(field: K, value: SMTPSettings[K]) => {
    setSettings(prev => {
      const next = { ...prev, [field]: value };
      // Auto-fill account name if user hasn't edited it manually
      if (field === 'provider' && !isUserEditedName) {
        const providerName = PROVIDERS.find(p => p.id === value)?.name || '';
        setAccountName(`${providerName} Sender`);
      }
      return next;
    });
    markDirty();
  };

  const openAddDialog = () => {
    setEditingId(null);
    setAccountName('Custom SMTP Sender');
    setIsUserEditedName(false);
    setCurrentStep(1);
    setSettings({
      provider: 'smtp',
      host: '',
      port: 587,
      encryption: 'tls',
      user: '',
      pass: '',
      from_email: '',
      from_name: '',
      auth: 1,
      api_key: '',
      domain: '',
      region: 'us',
      access_key: '',
      secret_key: ''
    });
    setStatusMessage(null);
    setIsDialogOpen(true);
  };

  const openEditDialog = (account: SMTPAccount) => {
    setEditingId(account.id);
    setAccountName(account.account_name);
    setIsUserEditedName(true);
    setCurrentStep(1);
    setSettings({
      ...account.config,
      provider: account.provider || 'smtp',
      pass: ''
    });
    setStatusMessage(null);
    setIsDialogOpen(true);
  };


  const deleteAccount = async (id: number) => {
    if (!confirm('Are you sure you want to delete this account?')) return;
    try {
      const resp = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/${id}`, {
        method: 'DELETE',
        headers: {
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        }
      });
      const result = await resp.json();
      if (result.success) {
        fetchAccounts();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'smtp-sender' } }));
      }
    } catch (error) {
      console.error('Failed to delete account:', error);
    }
  };

  const toggleAccount = async (id: number, active: boolean) => {
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/${id}/toggle`, {
        method: 'POST',
        headers: {
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({ active })
      });
      const result = await response.json();
      if (result.success) {
        fetchAccounts();
        window.dispatchEvent(new CustomEvent('wawp-refresh-data', { detail: { section: 'smtp-sender' } }));
      }
    } catch (error) {
      console.error('Failed to toggle account:', error);
    }
  };

  const testConnection = async () => {
    setIsTestingConnect(true);
    setStatusMessage(null);
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/validate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          provider: settings.provider,
          config: settings
        })
      });

      const result = await response.json();
      if (result.success) {
        setStatusMessage({ type: 'success', text: result.data?.message || 'Connection successful!' });
        if (editingId) fetchAccounts(); // Refresh to show validated status
      } else {
        const errorText = typeof result.data === 'string' ? result.data : (result.data?.message || result.message || 'Connection failed.');
        setStatusMessage({ type: 'error', text: errorText });
      }
    } catch {
      setStatusMessage({ type: 'error', text: 'An error occurred during test.' });
    }
    setIsTestingConnect(false);
  };

  const sendTestEmail = async () => {
    if (!testEmail) {
      setStatusMessage({ type: 'error', text: 'Please enter a test email address.' });
      return;
    }
    setIsTestingSend(true);
    setStatusMessage(null);
    try {
      const response = await fetch(`${dashboardData.global.apiRestUrl}/accounts/smtp/test`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          to: testEmail,
          id: editingId
        })
      });

      const result = await response.json();
      if (result.success) {
        setStatusMessage({ type: 'success', text: result.data || 'Test email sent successfully.' });
      } else {
        const errorText = typeof result.data === 'string' ? result.data : (result.data?.message || result.message || 'Failed to send test email.');
        setStatusMessage({ type: 'error', text: errorText });
      }
    } catch {
      setStatusMessage({ type: 'error', text: 'An error occurred.' });
    }
    setIsTestingSend(false);
  };

  const nextStep = () => setCurrentStep(prev => prev + 1);
  const prevStep = () => setCurrentStep(prev => prev - 1);

  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-6 animate-in fade-in duration-500 pb-12">

        {/* Header */}
        <SettingsHeader
          title="SMTP Mail Server"
          description="Route system emails through your own private mail server. Support multiple accounts."
          backUrl="admin.php?page=wawp&wawp_section=senders"
          className="mb-8"
        >
          <AdminButton onClick={openAddDialog} icon={Plus}>
            Add Account
          </AdminButton>
        </SettingsHeader>

        {/* Accounts Table */}
        <SettingCard className="p-0 overflow-hidden border-slate-100 shadow-sm bg-white">
          <ModernCardHeader
            iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`}
            title="SMTP Accounts"
            description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">Manage configurations and validation status</span>}
          />
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-y border-slate-100 bg-slate-50/50">
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">Default Sender</th>
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">Account Name</th>
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">Provider</th>
                  <th className="px-6 py-4 text-[10px] font-bold uppercase tracking-widest text-slate-400">Server Status</th>
                  <th className="px-6 py-4 text-right text-[10px] font-bold uppercase tracking-widest text-slate-400">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {isLoading ? (
                  null
                ) : accounts.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-6 py-12 text-center text-slate-400 text-sm italic">No accounts configured yet.</td>
                  </tr>
                ) : accounts.map((account) => (
                  <tr key={account.id} className="hover:bg-slate-50/50 transition-colors group">
                    <td className="px-6 py-4">
                      {account.is_active ? (
                        <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-600 text-white text-[10px] font-bold uppercase tracking-widest shadow-sm">
                          <ShieldCheck className="w-3 h-3" /> Selected
                        </span>
                      ) : (
                        <GhostButton
                          onClick={() => toggleAccount(account.id, true)}
                          className="h-7 px-3 text-[10px] font-bold uppercase tracking-widest text-slate-400 hover:text-[#004449] hover:bg-slate-100"
                        >
                          Set Default
                        </GhostButton>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex flex-col">
                        <span className="text-sm font-bold text-slate-700">{account.account_name}</span>
                        {account.provider === 'smtp' && (
                          <span className="text-[10px] font-medium text-slate-400 font-mono mt-0.5">{account.config?.host}:{account.config?.port}</span>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded bg-slate-50 border border-slate-100 flex items-center justify-center">
                          {(() => {
                            const p = PROVIDERS.find(p => p.id === account.provider);
                            return p?.iconPath ? <img src={p.iconPath} className="w-3.5 h-3.5 object-contain" /> : <Globe className="w-3.5 h-3.5 text-slate-400" />;
                          })()}
                        </div>
                        <span className="text-xs font-bold text-slate-600 uppercase tracking-wide">
                          {PROVIDERS.find(p => p.id === account.provider)?.name || account.provider}
                        </span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      {account.validated ? (
                        <span className="inline-flex items-center gap-1.5 text-emerald-600 text-[10px] font-bold uppercase tracking-widest">
                          <CheckCircle2 className="w-3.5 h-3.5" /> Active
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1.5 text-amber-500 text-[10px] font-bold uppercase tracking-widest">
                          <ClockIcon className="w-3.5 h-3.5" /> Pending Setup
                        </span>
                      )}
                    </td>
                    <td className="px-6 py-4 text-right">
                      <div className="flex items-center justify-end gap-2 opacity-100">
                        <SecondaryButton onClick={() => openEditDialog(account)} className="h-8 px-3 text-[10px] font-bold uppercase tracking-widest text-blue-600 border-blue-100 hover:bg-blue-50 rounded-[4px]" icon={Settings2}>
                          Edit & Test
                        </SecondaryButton>
                        <GhostButton onClick={() => deleteAccount(account.id)} size="icon-sm" className="text-rose-500 hover:text-rose-600 hover:bg-rose-50 rounded-[4px]" icon={Trash2}>
                          {null}
                        </GhostButton>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </SettingCard>

        {/* Dialog: 3-Step Wizard */}
        <Sheet open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <SheetContent side="right" className="w-full lg:max-w-[calc(100%-280px)] xl:max-w-[1200px] p-0 overflow-hidden border-none shadow-2xl flex flex-col h-full">

            <div className="bg-slate-50 border-b border-slate-100 sticky top-0 z-10">
              <ModernCardHeader
                title={editingId ? 'Edit Account' : 'Connect New Mail Server'}
                description={
                  <div className="text-[10px] font-bold uppercase tracking-widest">
                    <span className="text-[#004449]">Step {currentStep} of 3</span> — {currentStep === 1 ? 'Choose Delivery Method' : currentStep === 2 ? 'Configure Credentials' : 'Diagnostic Check'}
                  </div>
                }
                iconPath={`${dashboardData?.global?.pluginUrl}assets/img/senders/gmail.svg`}
                rightAction={
                  <GhostButton 
                    onClick={() => setIsDialogOpen(false)} 
                    size="icon-sm" 
                    className="text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full" 
                    icon={X}
                  >
                    {null}
                  </GhostButton>
                }
              />
              {/* Progress Bar Container */}
              <div className="h-1 bg-slate-200 w-full overflow-hidden">
                <div
                  className="h-full bg-[#004449] transition-all duration-700 ease-in-out"
                  style={{ width: `${(currentStep / 3) * 100}%` }}
                />
              </div>
            </div>

            <div className="flex-1 overflow-y-auto bg-white">
              <div className="p-8 max-w-4xl mx-auto space-y-12">
                {statusMessage && (
                  <div className={`p-4 rounded-xl border flex items-start gap-3 text-sm font-bold animate-in zoom-in duration-300 ${statusMessage.type === 'success' ? 'bg-emerald-50 border-emerald-100 text-emerald-700' : 'bg-rose-50 border-rose-100 text-rose-700'}`}>
                    {statusMessage.type === 'success' ? <CheckCircle2 className="w-5 h-5 mt-0.5 shrink-0" /> : <ShieldCheck className="w-5 h-5 mt-0.5 shrink-0" />}
                    <span className="whitespace-pre-wrap leading-relaxed flex-1">
                      {typeof statusMessage.text === 'string' ? statusMessage.text : JSON.stringify(statusMessage.text)}
                    </span>
                    <button onClick={() => setStatusMessage(null)}><X className="w-4 h-4 opacity-50" /></button>
                  </div>
                )}

                {/* STEP 1: CHOOSE SENDER */}
                {currentStep === 1 && (
                  <div className="space-y-10 animate-in fade-in slide-in-from-right-8 duration-500 ease-out">
                    <div className="space-y-4">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                        <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">Provider Selection</span>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {PROVIDERS.map((p) => (
                          <MethodButton
                            key={p.id}
                            active={settings.provider === p.id}
                            onClick={() => handleInputChange('provider', p.id)}
                            label={p.name}
                            description={p.desc}
                            iconPath={p.iconPath}
                            activeStyles="bg-white border-[#004449] ring-4 ring-[#004449]/5"
                          />
                        ))}
                      </div>
                      <div className="mt-4">
                        <StatusMessage
                          type={settings.provider === 'wp' ? 'active' : 'inactive'}
                          message={settings.provider === 'wp' 
                            ? "Using the default WordPress mailer. Simple and reliable, but subject to hosting limitations." 
                            : "Using a custom mail server. This allows for higher delivery rates and professional branding."}
                        />
                      </div>
                    </div>

                    <div className="space-y-4 pt-4">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                        <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">Management</span>
                      </div>
                      <div className="space-y-2">
                        <SettingInput
                          label="Account Friendly Name"
                          value={accountName}
                          onChange={(val) => {
                            setAccountName(val);
                            setIsUserEditedName(true);
                          }}
                          placeholder="e.g. Sales Team SMTP"
                          icon={Tag}
                        />
                        <p className="text-[10px] text-slate-400 font-medium italic">This name is only for your reference in the dashboard.</p>
                      </div>
                    </div>
                  </div>
                )}

                {/* STEP 2: CONFIGURATION */}
                {currentStep === 2 && (
                  <div className="space-y-10 animate-in fade-in slide-in-from-right-8 duration-500 ease-out">
                    <div className="space-y-4">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                        <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">Connection Credentials for {PROVIDERS.find(p => p.id === settings.provider)?.name}</span>
                        <ClockIcon className="w-3.5 h-3.5 text-[#004449] ml-auto opacity-40" />
                      </div>

                      {/* ─── Provider Preset Picker (Custom SMTP only) ─── */}
                      {settings.provider === 'smtp' && (() => {
                        const CATS: Record<string, string> = { popular: 'Popular', transactional: 'Transactional', hosting: 'Hosting', enterprise: 'Enterprise', regional: 'Regional / ISP' };
                        const q = presetSearch;
                        const filtered = SMTP_PRESETS.filter(p => !q || p.name.toLowerCase().includes(q.toLowerCase()) || p.host.toLowerCase().includes(q.toLowerCase()));
                        const activePreset = SMTP_PRESETS.find(p => settings.host === p.host && Number(settings.port) === p.port);
                        return (
                          <div className="mb-6 space-y-3">
                            <div className="flex items-center gap-2">
                              <span className="text-[10px] font-black uppercase tracking-widest text-slate-400">Quick-fill from a known provider</span>
                              <div className="flex-1 h-px bg-slate-100" />
                              <span className="text-[9px] font-bold text-slate-300 uppercase">{SMTP_PRESETS.length} Providers</span>
                            </div>
                            <input
                              type="text"
                              placeholder="Search providers... (e.g. Gmail, Hostinger, SendGrid)"
                              value={q}
                              onChange={(e) => setPresetSearch(e.target.value)}
                              className="w-full h-9 px-3 rounded-[5px] border border-slate-200 bg-white text-xs font-medium text-slate-700 placeholder:text-slate-300 focus:ring-1 focus:ring-[#004449]/30 focus:border-[#004449]/30 outline-none transition-all"
                            />
                            <div className="max-h-[280px] overflow-y-auto rounded-[5px] border border-slate-100 bg-slate-50/30 p-3 space-y-4">
                              {Object.entries(CATS).map(([catKey, catLabel]) => {
                                const items = filtered.filter(p => p.category === catKey);
                                if (items.length === 0) return null;
                                return (
                                  <div key={catKey}>
                                    <div className="text-[9px] font-black uppercase tracking-[0.2em] text-slate-300 mb-2 pl-1">{catLabel}</div>
                                    <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-1.5">
                                      {items.map((preset) => {
                                        const isActive = settings.host === preset.host && Number(settings.port) === preset.port;
                                        return (
                                          <button
                                            key={preset.id}
                                            type="button"
                                            onClick={() => {
                                              handleInputChange('host', preset.host);
                                              handleInputChange('port', preset.port);
                                              handleInputChange('encryption', preset.encryption);
                                              handleInputChange('auth', preset.auth);
                                            }}
                                            title={preset.hint || preset.name}
                                            className={`flex items-center gap-2 px-2.5 py-2 rounded-[5px] border text-left transition-all text-[11px] font-bold ${isActive
                                              ? 'bg-[#004449]/5 border-[#004449]/30 text-[#004449] ring-1 ring-[#004449]/20'
                                              : 'bg-white border-slate-200/80 text-slate-600 hover:border-slate-300 hover:bg-white'
                                              }`}
                                          >
                                            <img
                                              src={`${dashboardData?.global?.pluginUrl}${preset.iconFile}`}
                                              className="w-3.5 h-3.5 object-contain shrink-0"
                                              alt=""
                                              onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                                            />
                                            <span className="truncate">{preset.name}</span>
                                          </button>
                                        );
                                      })}
                                    </div>
                                  </div>
                                );
                              })}
                              {filtered.length === 0 && (
                                <p className="text-center text-xs text-slate-400 py-6">No providers match your search.</p>
                              )}
                            </div>
                            {activePreset?.hint && (
                              <p className="text-[10px] text-amber-700 bg-amber-50 border border-amber-100 rounded-[5px] px-3 py-2 font-medium">
                                💡 {activePreset.hint}
                              </p>
                            )}
                          </div>
                        );
                      })()}

                      {settings.provider === 'wp' ? (
                        <div className="p-10 rounded-2xl bg-blue-50 border-2 border-dashed border-blue-200 flex flex-col items-center text-center gap-4 py-16">
                          <div className="w-20 h-20 rounded-[2.5rem] bg-blue-100 flex items-center justify-center text-blue-600 shadow-inner">
                            <img src={`${dashboardData?.global?.pluginUrl}assets/img/senders/postman.svg`} className="w-10 h-10 opacity-80 object-contain" alt="" />
                          </div>
                          <div className="space-y-2">
                            <h4 className="font-bold text-blue-950 text-xl">System Integration Ready</h4>
                            <p className="text-sm text-blue-700/80 font-medium max-w-sm mx-auto">
                              Wawp will use your server's default mailer. Ensure your hosting provider supports PHPMailer or has sendmail configured.
                            </p>
                          </div>
                        </div>
                      ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 bg-slate-50/50 p-8 rounded-2xl border border-slate-100 shadow-sm">
                          <SettingInput
                            label="SMTP Host"
                            value={settings.host || ''}
                            onChange={(val) => handleInputChange('host', val)}
                            placeholder="smtp.gmail.com"
                            icon={Globe}
                          />
                          <SettingInput
                            label="Port"
                            type="number"
                            value={String(settings.port || '')}
                            onChange={(val) => handleInputChange('port', Number(val))}
                            placeholder="587"
                            icon={Hash}
                          />
                          <div className="space-y-2">
                            <Label className="text-xs font-bold text-slate-700 uppercase tracking-widest">Encryption</Label>
                            <SearchableSelect
                              options={[
                                { value: "none", label: "None" },
                                { value: "ssl", label: "SSL" },
                                { value: "tls", label: "TLS" }
                              ]}
                              value={settings.encryption || "tls"}
                              onChange={(v) => handleInputChange('encryption', v)}
                              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="space-y-2">
                            <Label className="text-xs font-bold text-slate-700 uppercase tracking-widest">Authentication</Label>
                            <div className="flex items-center justify-between px-4 bg-white border border-slate-200 rounded-lg shadow-none min-h-[40px]">
                              <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Login Required</span>
                              <Switch checked={!!settings.auth} onCheckedChange={(c) => handleInputChange('auth', c ? 1 : 0)} />
                            </div>
                          </div>

                          {!!settings.auth && (
                            <div className="md:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 pt-4 mt-2 border-t border-slate-200/50">
                              <SettingInput
                                label="Username"
                                value={settings.user || ''}
                                onChange={(val) => handleInputChange('user', val)}
                                placeholder="user@example.com"
                                icon={User}
                              />
                              <SettingInput
                                label="Password"
                                type="password"
                                value={settings.pass || ''}
                                onChange={(val) => handleInputChange('pass', val)}
                                placeholder="••••••••"
                                icon={Lock}
                              />
                            </div>
                          )}
                        </div>
                      )}
                      <div className="mt-4">
                        <StatusMessage
                          type={(settings.provider === 'wp' || (settings.host && settings.port)) ? 'active' : 'error'}
                          message={(settings.provider === 'wp' || (settings.host && settings.port)) 
                            ? "Server connection details are configured. You can proceed to test the delivery." 
                            : "Connection details missing. Please enter your SMTP host and port to continue."}
                        />
                      </div>
                    </div>

                    {/* Common Identity for Sender */}
                    <div className="space-y-4 pt-4">
                      <div className="flex items-center gap-2 mb-2">
                        <div className="w-1.5 h-4 bg-[#004449] rounded-full" />
                        <span className="text-[10px] font-bold uppercase tracking-widest text-[#004449]">Public Identity</span>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 bg-white p-6 rounded-2xl border border-slate-100">
                        <SettingInput
                          label="From Email"
                          type="email"
                          value={settings.from_email || ''}
                          onChange={(val) => handleInputChange('from_email', val)}
                          placeholder="site@wawp.net"
                          icon={Mail}
                        />
                        <SettingInput
                          label="From Name"
                          value={settings.from_name || ''}
                          onChange={(val) => handleInputChange('from_name', val)}
                          placeholder="Wawp Support"
                          icon={UserCircle}
                        />
                      </div>
                    </div>
                  </div>
                )}

                {/* STEP 3: TEST */}
                {currentStep === 3 && (
                  <div className="space-y-10 animate-in fade-in slide-in-from-right-8 duration-500 ease-out">
                    <SettingCard className="p-0 overflow-hidden border-slate-100 shadow-sm bg-white">
                      <ModernCardHeader
                        iconPath={`${dashboardData?.global?.pluginUrl}assets/icons/shield.svg`}
                        title="Verification & Testing"
                        description={<span className="text-[10px] uppercase font-bold tracking-[0.2em] text-[#004449]">Validate Endpoint Sync & Send Direct Mail</span>}
                      />
                      <div className="p-8 bg-slate-50/50">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
                          {/* Connection Check */}
                          <div className="flex flex-col gap-4">
                            <div>
                              <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2">
                                <Globe className="w-4.5 h-4.5 text-[#004449]" /> Server Integration
                              </h4>
                              <p className="text-[11px] font-medium text-slate-500 leading-relaxed mt-1.5">
                                Verify that the plugin can successfully connect to your SMTP server using the provided credentials.
                              </p>
                            </div>
                            <div className="mt-auto pt-2">
                              <AdminButton
                                onClick={testConnection}
                                disabled={isTestingConnect}
                                className="w-full bg-slate-900 hover:bg-black uppercase tracking-widest"
                                icon={isTestingConnect ? RefreshCw : ShieldCheck}
                                loading={isTestingConnect}
                              >
                                Run Server Check
                              </AdminButton>
                            </div>
                          </div>

                          {/* Email Check */}
                          <div className="flex flex-col gap-4 relative">
                            {/* Vertical divider on desktop */}
                            <div className="hidden md:block absolute -left-5 top-0 bottom-0 w-px bg-slate-200/60" />

                            <div>
                              <h4 className="font-bold text-slate-800 text-sm flex items-center gap-2">
                                <Send className="w-4.5 h-4.5 text-[#004449]" /> Direct Mail Test
                              </h4>
                              <p className="text-[11px] font-medium text-slate-500 leading-relaxed mt-1.5">
                                Send a physical test email to ensure messages are routed and delivered correctly without ending up in spam.
                              </p>
                            </div>
                            <div className="flex gap-2 mt-auto pt-2">
                              <SettingInput
                                label="Test Email Address"
                                value={testEmail}
                                onChange={(val) => setTestEmail(val)}
                                placeholder="to@example.com"
                                icon={Send}
                                className="flex-1"
                              />
                              <div className="pt-7">
                                <AdminButton
                                  onClick={sendTestEmail}
                                  disabled={isTestingSend}
                                  className="px-5 active:scale-95 transition-all shadow-md shadow-[#004449]/10"
                                  icon={isTestingSend ? RefreshCw : ChevronRight}
                                  loading={isTestingSend}
                                >
                                  {null}
                                </AdminButton>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </SettingCard>

                    <div className="p-6 rounded-xl bg-amber-50/50 border border-amber-100/50 flex items-start gap-4">
                      <Zap className="w-5 h-5 text-amber-600 mt-1 shrink-0" />
                      <div className="space-y-1">
                        <p className="text-[10px] font-black text-amber-800 uppercase tracking-widest">Configuration Note</p>
                        <p className="text-[11px] text-amber-700/80 leading-relaxed font-medium mt-1">
                          It is highly recommended to perform a successful test before finalizing. Accounts with a failed test will remain in <span className="font-black text-amber-600">"Pending"</span> status and might not route emails correctly.
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="p-6 bg-slate-50 border-t border-slate-100 sticky bottom-0 z-10 flex flex-row gap-3">
              <SecondaryButton onClick={() => setIsDialogOpen(false)} className="flex-1 rounded-lg font-bold text-slate-500 hover:bg-white active:scale-95 transition-all text-xs uppercase tracking-widest border border-transparent hover:border-slate-200">
                Close
              </SecondaryButton>

              {currentStep > 1 && (
                <GhostButton onClick={prevStep} className="flex-1 rounded-lg font-bold text-slate-500 hover:bg-white active:scale-95 transition-all text-xs uppercase tracking-widest border border-transparent hover:border-slate-200" icon={ArrowLeft}>
                  Back
                </GhostButton>
              )}

              {currentStep < 3 ? (
                <AdminButton onClick={nextStep} className="flex-[2] text-xs uppercase tracking-[0.15em] shadow-md shadow-teal-900/5">
                  Continue Setup
                  <ArrowRight className="w-3.5 h-3.5 ml-2" />
                </AdminButton>
              ) : (
                <SaveWithStatus
                  saveStatus={saveStatus}
                  hasUnsavedChanges={hasUnsavedChanges}
                  isSaving={isSaving}
                  onSave={() => handleSave(false)}
                  t={{
                    saveChanges: editingId ? 'Update Settings' : 'Initialize Account'
                  }}
                />
              )}
            </div>
          </SheetContent>
        </Sheet>
      </div>
    </SettingsLayout>
  );
}
