import { useState, useEffect } from 'react';
import type { DashboardData } from './types';
import {
  LogIn,
  UserPlus,
  Zap,
  ArrowRightLeft,
  ShoppingBag,
  Bell,
  Smartphone,
  Lock,
  Copy,
  FileType,
  CheckCircle2,
  Save,
  ExternalLink,
  Flame,
  Sparkles
} from 'lucide-react';
import { toast } from "sonner";
import { motion, AnimatePresence } from "framer-motion";
import { Switch } from './components/ui/switch';
import { 
  SettingCard, 
  FlatTabs, 
  ModernCardHeader,
  StatusMessage,
  MethodButton,
  BannerCard,
  SettingInput,
  ShortcodeGrid,
  SettingsLayout,
  SettingsHeader,
  PrimaryButton,
} from './components/ui/settings-ui';
import WhatsAppAuthSettings from './components/common/WhatsAppAuthSettings';

interface PageOption {
  id: number;
  title: string;
  url: string;
  edit: string;
}

interface AuthPagesData {
  currentTab: string;
  pages: PageOption[];
  options: Record<string, string | number>;
  optionNames: Record<string, string>;
  createUrls: {
    login: string;
    signup: string;
    fast_login: string;
  };
  wcMyAccountId?: string;
  firebaseConfigured: boolean;
  i18n: Record<string, string>;
}


interface AuthenticationPagesSettingsProps {
  data: DashboardData;
}

const AuthenticationPagesSettings: React.FC<AuthenticationPagesSettingsProps> = ({ data: rootData }) => {
  const data = (rootData?.authPages as unknown as AuthPagesData);
  const msgs = rootData?.status_messages || {};

  const [activeTab, setActiveTab] = useState(data?.currentTab || 'tab-login-signup-pages');
  const [settings, setSettings] = useState(data?.options || {});
  const [isSaving, setIsSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');

  useEffect(() => {
    if (data?.options) {
      setSettings(data.options);
      if (data.currentTab) setActiveTab(data.currentTab);
    }
  }, [data]);

  if (!data) return null;

  const t = data?.i18n || {};

  const getStatus = (id: string): { type: 'active' | 'inactive' | 'error' | 'warning', message: string } | null => {
    const isChecked = (key: string) => settings[data?.optionNames?.[key] || ''] == 1;

    switch (id) {
      case 'login': {
        const pageId = settings[data.optionNames.loginPage];
        const page = data.pages.find(p => p.id == pageId);
        return page
          ? { type: 'active', message: (msgs.pages_login_active || '').replace('%s', `<b>${page.title}</b>`) }
          : { type: 'inactive', message: msgs.pages_inactive || '' };
      }
      case 'signup': {
        const pageId = settings[data.optionNames.signupPage];
        const page = data.pages.find(p => p.id == pageId);
        return page
          ? { type: 'active', message: (msgs.pages_signup_active || '').replace('%s', `<b>${page.title}</b>`) }
          : { type: 'inactive', message: msgs.pages_inactive || '' };
      }
      case 'fast_login': {
        const pageId = settings[data.optionNames.fastLoginPage];
        const page = data.pages.find(p => p.id == pageId);
        return page
          ? { type: 'active', message: (msgs.pages_fast_login_ready || '').replace('%s', `<b>${page.title}</b>`) }
          : { type: 'inactive', message: msgs.pages_inactive || '' };
      }
      case 'redirectWpLogin':
        if (isChecked('redirectWpLogin')) {
          const loginPage = data?.pages?.find(p => p.id == settings[data?.optionNames?.loginPage || '']);
          return {
            type: 'active',
            message: (msgs.pages_redirect_login_a || '')
              .replace('%1$s', '<code>wp-login.php</code>')
              .replace('%2$s', `<b>${loginPage?.title || 'Custom Login Page'}</b>`)
          };
        }
        return { type: 'inactive', message: msgs.pages_redirect_login_i || '' };

      case 'redirectMyAccount': {
        const isLoop = isChecked('redirectMyAccount') && settings[data.optionNames.loginPage] && data.wcMyAccountId && settings[data.optionNames.loginPage] == data.wcMyAccountId;
        if (isLoop) return { type: 'error', message: msgs.pages_redirect_error || '' };
        if (isChecked('redirectMyAccount')) {
          const loginPage = data.pages.find(p => p.id == settings[data.optionNames.loginPage]);
          return { type: 'active', message: (msgs.pages_redirect_acc_a || '').replace('%s', `<b>${loginPage?.title || 'Custom Login Page'}</b>`) };
        }
        return { type: 'inactive', message: msgs.pages_redirect_acc_i || '' };
      }
      case 'replaceWcForms':
        return isChecked('replaceWcForms')
          ? { type: 'active', message: msgs.pages_replace_wc_a || '' }
          : { type: 'inactive', message: msgs.pages_replace_wc_i || '' };

      case 'showPhoneBar':
        return isChecked('showPhoneBar')
          ? { type: 'active', message: msgs.pages_phone_bar_a || '' }
          : { type: 'inactive', message: msgs.pages_phone_bar_i || '' };

      case 'showPhoneBarGlobal':
        if (!isChecked('showPhoneBar') && isChecked('showPhoneBarGlobal')) return { type: 'warning', message: msgs.pages_phone_bar_required || '' };
        return isChecked('showPhoneBarGlobal')
          ? { type: 'active', message: msgs.pages_phone_bar_global_a || '' }
          : { type: 'inactive', message: msgs.pages_phone_bar_global_i || '' };

      case 'showPrefs':
        return isChecked('showPrefs')
          ? { type: 'active', message: msgs.pages_user_prefs_a || '' }
          : { type: 'inactive', message: msgs.pages_user_prefs_i || '' };

      default: return null;
    }
  };

  const handleSave = async (newSettings = settings) => {
    setIsSaving(true);
    setSaveStatus('saving');

    try {
      const settingsToSave: Record<string, string | number> = {};
      
      // Map frontend keys to database option names via optionNames map
      (Object.keys(newSettings) as (keyof typeof newSettings)[]).forEach(key => {
        const dbKey = data?.optionNames?.[key] || key;
        settingsToSave[dbKey] = newSettings[key];
      });

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

      if (!response.ok) {
        throw new Error(`Server responded with ${response.status}`);
      }

      const result = await response.json();
      const resultMsg = result.message || (result.data && result.data.message);
      
      if (result.success) {
        setSaveStatus('saved');
        window.dispatchEvent(new CustomEvent('wawp-refresh-data'));
        toast.success(typeof resultMsg === 'string' ? resultMsg : t.settings_saved_notice);
      } else {
        setSaveStatus('error');
        toast.error(typeof resultMsg === 'string' ? resultMsg : t.errorOccurred);
      }
    } catch (error) {
      console.error('AuthPages save error:', error);
      setSaveStatus('error');
      toast.error(t.errorOccurred);
    } finally {
      setIsSaving(false);
      setTimeout(() => setSaveStatus('idle'), 3000);
    }
  };

  const updateSetting = (key: string, value: string | number) => {
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);
    handleSave(newSettings);
  };

  const tabs = [
    { id: 'tab-login-signup-pages', label: 'Custom Pages', icon: FileType },
    { id: 'tab-redirect-settings', label: 'Redirect Rules', icon: ArrowRightLeft },
    { id: 'tab-account-integration', label: 'WC Integration', icon: ShoppingBag },
    { id: 'tab-shortcodes', label: 'Copy Shortcodes', icon: Copy },
  ];

  const shortcodesList = [
    { title: t.otp_login_title, description: t.otp_login_desc, code: '[wawp_otp_login]', icon: Lock },
    { title: t.otp_signup_title, description: t.otp_signup_desc, code: '[wawp_signup_form]', icon: UserPlus },
    { title: t.fast_login_title, description: t.fast_login_desc, code: '[wawp-fast-login]', icon: Zap },
    { title: t.checkout_otp_title, description: t.checkout_otp_desc, code: '[woocommerce_checkout]', icon: ShoppingBag },
    { title: t.user_prefs_title, description: t.user_prefs_desc, code: '[wawp_notification_prefs]', icon: Bell },
    { title: t.verify_phone_title, description: t.verify_phone_desc, code: '[wawp_phone_verification_bar]', icon: Smartphone },
  ];

  return (
    <SettingsLayout>
      <SettingsHeader 
        title={t.authentication_pages_title || 'Authentication Pages'} 
        description={t.authentication_pages_desc || 'Deploy custom login, signup and verification landing pages.'}
      >
        {saveStatus === 'saved' && (
          <div className="hidden md:flex items-center gap-2 px-3 py-1.5 bg-emerald-50 text-emerald-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-emerald-100/50"
          >
            <CheckCircle2 size={14} />
            Cloud Deployment Finished
          </div>
        )}
        <PrimaryButton 
          onClick={() => handleSave()}
          loading={isSaving}
          icon={Save}
          className="h-10 px-10"
        >
          {isSaving ? 'Synchronizing...' : 'Commit Changes'}
        </PrimaryButton>
      </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 === 'tab-login-signup-pages' && (
                <div className="space-y-8 max-w-5xl animate-in slide-in-from-right-4 duration-500">
                  {[
                    { type: 'login', icon: LogIn, titleKey: 'login_settings_title', descKey: 'login_page_desc', opt: 'loginPage' },
                    { type: 'signup', icon: UserPlus, titleKey: 'signup_settings_title', descKey: 'signup_page_desc', opt: 'signupPage' },
                    { type: 'fast_login', icon: Zap, titleKey: 'fast_login_settings_title', descKey: 'fast_login_page_desc', opt: 'fastLoginPage' }
                  ].map((item) => {
                    const optionName = data.optionNames[item.opt as keyof typeof data.optionNames];
                    const selectedId = settings[optionName];
                    const selectedPage = data.pages.find(p => p.id == selectedId);
                    const status = getStatus(item.type);

                    return (
                      <SettingCard key={item.type} className="p-0 overflow-hidden">
                        <ModernCardHeader 
                          title={t[item.titleKey]} 
                          description={t[item.descKey]}
                          icon={item.icon}
                        />

                        <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 Page Selection</label>
                             <div className="flex flex-col md:flex-row gap-4">
                                <select
                                    value={selectedId || ''}
                                    onChange={(e) => updateSetting(optionName, e.target.value)}
                                    className="flex-1 h-11 px-4 bg-slate-50/50 border border-slate-200 rounded-[5px] focus:bg-white focus:border-[#004449] outline-none transition-all text-sm font-bold shadow-none"
                                >
                                    <option value="">{t.select_page_placeholder}</option>
                                    {data.pages.map(p => (
                                      <option key={p.id} value={p.id}>{p.title}</option>
                                    ))}
                                </select>

                                <div className="flex gap-2">
                                  {selectedPage ? (
                                    <>
                                      <a href={selectedPage.url} target="_blank" rel="noreferrer" className="px-6 flex items-center justify-center gap-2 h-11 bg-[#004449] hover:bg-[#003337] !text-white text-[12px] font-black rounded-[5px] transition-all">
                                        Preview <ExternalLink size={14} />
                                      </a>
                                      <a href={selectedPage.edit} target="_blank" rel="noreferrer" className="px-6 flex items-center justify-center gap-2 h-11 bg-white border border-[#dcdcde] text-slate-900 text-[12px] font-black rounded-[5px] hover:bg-slate-50 transition-all">
                                        Edit Layout
                                      </a>
                                    </>
                                  ) : (
                                    <a href={data.createUrls[item.type as keyof typeof data.createUrls]} className="px-6 flex items-center justify-center gap-2 h-11 bg-white border border-[#dcdcde] text-slate-900 text-[12px] font-black rounded-[5px] hover:bg-slate-50 transition-all">
                                      Instantiate Page
                                    </a>
                                  )}
                                </div>
                             </div>
                           </div>
                           
                           {status && <StatusMessage {...status} />}
                        </div>
                      </SettingCard>
                    );
                  })}
                </div>
              )}

              {activeTab === 'tab-redirect-settings' && (
                <div className="space-y-6 max-w-5xl animate-in slide-in-from-right-4 duration-500">
                  <SettingCard className="p-0 overflow-hidden">
                    <ModernCardHeader 
                      title={t.redirect_wp_login_label} 
                      description={t.redirect_wp_login_desc}
                      icon={ArrowRightLeft}
                      rightAction={
                        <Switch 
                          checked={settings[data.optionNames.redirectWpLogin] == 1}
                          onCheckedChange={(checked) => updateSetting(data.optionNames.redirectWpLogin, checked ? 1 : 0)}
                        />
                      }
                    />
                    <div className="p-6 md:p-8">
                      <StatusMessage {...getStatus('redirectWpLogin')!} />
                    </div>
                  </SettingCard>

                  <SettingCard className="p-0 overflow-hidden">
                    <ModernCardHeader 
                      title={t.redirect_my_account_label} 
                      description={t.redirect_my_account_desc}
                      icon={ShoppingBag}
                      rightAction={
                        <Switch 
                          checked={settings[data.optionNames.redirectMyAccount] == 1}
                          onCheckedChange={(checked) => updateSetting(data.optionNames.redirectMyAccount, checked ? 1 : 0)}
                        />
                      }
                    />
                    <div className="p-6 md:p-8">
                      <StatusMessage {...getStatus('redirectMyAccount')!} />
                    </div>
                  </SettingCard>
                </div>
              )}

              {activeTab === 'tab-account-integration' && (
                <div className="space-y-6 max-w-5xl animate-in slide-in-from-right-4 duration-500">
                  <SettingCard className="p-0 overflow-hidden">
                    <ModernCardHeader 
                      title={t.replace_wc_forms_label} 
                      description={t.replace_wc_forms_desc}
                      icon={ShoppingBag}
                      rightAction={
                        <Switch 
                          checked={settings[data.optionNames.replaceWcForms] == 1}
                          onCheckedChange={(checked) => updateSetting(data.optionNames.replaceWcForms, checked ? 1 : 0)}
                        />
                      }
                    />
                    <div className="p-6 md:p-8">
                      <StatusMessage {...getStatus('replaceWcForms')!} />
                    </div>
                  </SettingCard>

                  <SettingCard className="p-0 overflow-hidden">
                    <ModernCardHeader 
                      title={t.show_prefs_label} 
                      description={t.show_prefs_desc}
                      icon={Bell}
                      rightAction={
                        <Switch 
                          checked={settings[data.optionNames.showPrefs] == 1}
                          onCheckedChange={(checked) => updateSetting(data.optionNames.showPrefs, checked ? 1 : 0)}
                        />
                      }
                    />
                    <div className="p-6 md:p-8">
                      <StatusMessage {...getStatus('showPrefs')!} />
                    </div>
                  </SettingCard>

                  <SettingCard className="p-0 overflow-hidden">
                    <ModernCardHeader 
                      title={t.show_phone_bar_label} 
                      description={t.show_phone_bar_desc}
                      icon={Smartphone}
                      rightAction={
                        <Switch 
                          checked={settings[data.optionNames.showPhoneBar] == 1}
                          onCheckedChange={(checked) => updateSetting(data.optionNames.showPhoneBar, checked ? 1 : 0)}
                        />
                      }
                    />
                    <div className="p-6 md:p-8">
                      <StatusMessage {...getStatus('showPhoneBar')!} />

                    <AnimatePresence>
                      {settings[data.optionNames.showPhoneBar] == 1 && (
                        <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }} className="overflow-hidden">
                           <div className="mt-8 pt-8 border-t border-slate-100 space-y-10">
                              <div className="space-y-4">
                                <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Identity Verification Flow</label>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                   <MethodButton 
                                     active={settings[data.optionNames.otpMethod] === 'whatsapp'} 
                                     label="WhatsApp Direct" 
                                     icon={Smartphone}
                                     activeStyles="border-emerald-500 bg-emerald-50/10"
                                     color="text-emerald-500"
                                     bg="bg-emerald-50"
                                     onClick={() => updateSetting(data.optionNames.otpMethod, 'whatsapp')}
                                   />
                                   <MethodButton 
                                     active={settings[data.optionNames.otpMethod] === 'firebase'} 
                                     label="Firebase SMS" 
                                     icon={Flame}
                                     disabled={!data.firebaseConfigured}
                                     activeStyles="border-orange-500 bg-orange-50/10"
                                     color="text-orange-500"
                                     bg="bg-orange-50"
                                     onClick={() => updateSetting(data.optionNames.otpMethod, 'firebase')}
                                   />
                                </div>
                                {!data.firebaseConfigured && settings[data.optionNames.otpMethod] === 'firebase' && (
                                   <StatusMessage type="error" message="<b>Firebase is not configured!</b> Please visit the Firebase Settings tab first." />
                                )}
                              </div>

                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                 <SettingInput 
                                   label="Global Bar Intro"
                                   value={String(settings[data.optionNames.phoneBarIntro] || '')}
                                   onChange={(val) => updateSetting(data.optionNames.phoneBarIntro, val)}
                                   placeholder="Your number is"
                                 />
                                 <SettingInput 
                                   label="Global Bar Outro"
                                   value={String(settings[data.optionNames.phoneBarOutro] || '')}
                                   onChange={(val) => updateSetting(data.optionNames.phoneBarOutro, val)}
                                   placeholder="Verify now."
                                 />
                              </div>

                              {settings[data.optionNames.otpMethod] === 'whatsapp' && (
                                <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                                   <BannerCard 
                                     title="Identity Message Template" 
                                     badge="Dynamic Injection" 
                                     color="emerald" 
                                     icon={Sparkles}
                                   />
                                   <div className="space-y-6 pt-4 border-t border-slate-100">
                                      <WhatsAppAuthSettings 
                                        settings={settings}
                                        updateSetting={updateSetting}
                                        optionNames={data.optionNames}
                                      />
                                   </div>
                                </motion.div>
                              )}
                           </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                    </div>
                  </SettingCard>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                     <SettingCard className="p-0 overflow-hidden">
                        <ModernCardHeader 
                          title={t.show_phone_bar_global_label} 
                          description="Display bar on all public pages." 
                          icon={Zap}
                          rightAction={
                            <Switch 
                              checked={settings[data.optionNames.showPhoneBarGlobal] == 1}
                              disabled={settings[data.optionNames.showPhoneBar] != 1}
                              onCheckedChange={(val) => updateSetting(data.optionNames.showPhoneBarGlobal, val ? 1 : 0)}
                            />
                          }
                        />
                        <div className="p-6">
                          <StatusMessage {...getStatus('showPhoneBarGlobal')!} />
                        </div>
                     </SettingCard>

                     <SettingCard className="p-0 overflow-hidden">
                        <ModernCardHeader 
                          title={t.lock_site_label} 
                          description="Enforce mandatory verification." 
                          icon={Lock}
                          rightAction={
                            <Switch 
                              checked={settings[data.optionNames.lockSite] == 1}
                              disabled={settings[data.optionNames.showPhoneBar] != 1}
                              onCheckedChange={(val) => updateSetting(data.optionNames.lockSite, val ? 1 : 0)}
                            />
                          }
                        />
                        <div className="p-6">
                          <StatusMessage type="warning" message="<b>Security Note:</b> Locking the site restricts all frontend access until verified." />
                        </div>
                     </SettingCard>
                  </div>
                </div>
              )}

              {activeTab === 'tab-shortcodes' && (
                <div className="animate-in slide-in-from-right-4 duration-500">
                  <ShortcodeGrid 
                    title="Frontend Integration"
                    description="Standardized blocks to embed authentication flows into any page or theme builder."
                    shortcodes={shortcodesList}
                  />
                </div>
              )}
            </motion.div>
          </AnimatePresence>
      </div>
    </SettingsLayout>
  );
};

export default AuthenticationPagesSettings;
