import React, { useState, useEffect } from 'react';
import type { DashboardData } from './types';
import {
  LogIn,
  UserPlus,
  Zap,
  ArrowRightLeft,
  ShoppingBag,
  Bell,
  Smartphone,
  Lock,
  Copy,
  FileType,
  ExternalLink,
  Heading,
  Info
} from 'lucide-react';
import { motion, AnimatePresence } from "framer-motion";
import { SearchableSelect } from './components/ui/searchable-select';
import { Switch } from './components/ui/switch';
import {
  SettingCard,
  FlatTabs,
  ModernCardHeader,
  StatusMessage,
  MethodButton,
  SettingInput,
  ShortcodeGrid,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  SecondaryButton,
  SaveWithStatus
} from './components/ui/settings-ui';
import { useSettingsSave } from './hooks/useSettingsSave';
import WhatsAppAuthSettings from './components/common/WhatsAppAuthSettings';

import { CompactSettingCard } from './components/ui/CompactSettingCard';

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 [prevData, setPrevData] = useState(data);

  const { saveStatus, hasUnsavedChanges, isSaving, handleSave, markDirty } = useSettingsSave({
    onSave: async () => {
      try {
        const settingsToSave: Record<string, string | number> = {};
        (Object.keys(settings) as (keyof typeof settings)[]).forEach(key => {
          const dbKey = data?.optionNames?.[key] || key;
          settingsToSave[dbKey] = settings[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 })
        });
        const result = await response.json();
        if (result.success) {
          window.dispatchEvent(new CustomEvent('wawp-refresh-data'));
          return true;
        }
        return false;
      } catch (error) {
        console.error('AuthPages save error:', error);
        return false;
      }
    }
  });

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

  useEffect(() => {
    const timer = setTimeout(() => {
      if (data !== prevData) {
        setPrevData(data);
        if (data?.options) {
          setSettings(data.options);
          if (data.currentTab) setActiveTab(data.currentTab);
        }
      }
    }, 0);
    return () => clearTimeout(timer);
  }, [data, prevData]);

  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 updateSetting = (key: string, value: string | number) => {
    setSettings(prev => ({ ...prev, [key]: value }));
    markDirty();
  };

  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>
      <div className="max-w-7xl mx-auto space-y-6">
        <SettingsHeader
          title={t.authentication_pages_title || 'Authentication Pages'}
          description={t.authentication_pages_desc || 'Deploy custom login, signup and verification landing pages.'}
        >
          <SaveWithStatus
            saveStatus={saveStatus}
            hasUnsavedChanges={hasUnsavedChanges}
            isSaving={isSaving}
            onSave={() => handleSave(false)}
            t={{
              saveChanges: 'Commit Changes',
              synchronized: 'Cloud Deployment Finished'
            }}
          />
        </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-7xl mx-auto 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">
                            <SearchableSelect
                              options={data.pages.map(p => ({ value: String(p.id), label: p.title }))}
                              value={String(selectedId || '')}
                              onChange={(val) => updateSetting(optionName, val)}
                              placeholder={t.select_page_placeholder}
                              className="flex-1 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 className="flex gap-2">
                              {selectedPage ? (
                                <>
                                  <AdminButton
                                    onClick={() => window.open(selectedPage.url, '_blank')}
                                    icon={ExternalLink}
                                  >
                                    Preview
                                  </AdminButton>
                                  <SecondaryButton
                                    onClick={() => window.open(selectedPage.edit, '_blank')}
                                  >
                                    Edit Layout
                                  </SecondaryButton>
                                </>
                              ) : (
                                <SecondaryButton
                                  onClick={() => window.location.href = data.createUrls[item.type as keyof typeof data.createUrls]}
                                >
                                  Instantiate Page
                                </SecondaryButton>
                              )}
                            </div>
                          </div>
                        </div>

                        {status && <StatusMessage {...status} />}
                      </div>
                    </SettingCard>
                  );
                })}
              </div>
            )}

            {activeTab === 'tab-redirect-settings' && (
              <div className="space-y-4 max-w-7xl mx-auto animate-in slide-in-from-right-4 duration-500">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <CompactSettingCard
                    title={t.redirect_wp_login_label}
                    description={t.redirect_wp_login_desc}
                    icon={ArrowRightLeft}
                    checked={settings[data.optionNames.redirectWpLogin] == 1}
                    onChange={(checked) => updateSetting(data.optionNames.redirectWpLogin, checked ? 1 : 0)}
                    statusMessage={getStatus('redirectWpLogin')?.message}
                    statusType={getStatus('redirectWpLogin')?.type}
                  />

                  <CompactSettingCard
                    title={t.redirect_my_account_label}
                    description={t.redirect_my_account_desc}
                    icon={ShoppingBag}
                    checked={settings[data.optionNames.redirectMyAccount] == 1}
                    onChange={(checked) => updateSetting(data.optionNames.redirectMyAccount, checked ? 1 : 0)}
                    statusMessage={getStatus('redirectMyAccount')?.message}
                    statusType={getStatus('redirectMyAccount')?.type}
                  />
                </div>
              </div>
            )}

            {activeTab === 'tab-account-integration' && (
              <div className="space-y-6 max-w-7xl mx-auto animate-in slide-in-from-right-4 duration-500">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <CompactSettingCard
                    title={t.replace_wc_forms_label}
                    description={t.replace_wc_forms_desc}
                    icon={ShoppingBag}
                    checked={settings[data.optionNames.replaceWcForms] == 1}
                    onChange={(checked) => updateSetting(data.optionNames.replaceWcForms, checked ? 1 : 0)}
                    statusMessage={getStatus('replaceWcForms')?.message}
                    statusType={getStatus('replaceWcForms')?.type}
                  />

                  <CompactSettingCard
                    title={t.show_prefs_label}
                    description={t.show_prefs_desc}
                    icon={Bell}
                    checked={settings[data.optionNames.showPrefs] == 1}
                    onChange={(checked) => updateSetting(data.optionNames.showPrefs, checked ? 1 : 0)}
                    statusMessage={getStatus('showPrefs')?.message}
                    statusType={getStatus('showPrefs')?.type}
                  />
                </div>

                <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 space-y-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-8">

                            <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=""
                                icon={Heading}
                                showEmoji={true}
                                showFormatting={true}
                              />
                              <SettingInput
                                label="Global Bar Outro"
                                value={String(settings[data.optionNames.phoneBarOutro] || '')}
                                onChange={(val) => updateSetting(data.optionNames.phoneBarOutro, val)}
                                placeholder=""
                                icon={Info}
                                showEmoji={true}
                                showFormatting={true}
                              />
                            </div>

                            <SettingCard className="p-0 overflow-hidden border-slate-100 shadow-none bg-slate-50/30">
                              <ModernCardHeader
                                title="Primary Phone Method"
                                description="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">
                                <MethodButton
                                  active={settings[data.optionNames.otpMethod] === 'whatsapp'}
                                  label="WhatsApp Web Authentication"
                                  iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg"}
                                  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 Authentication"
                                  iconPath={(rootData.global?.pluginUrl || '') + "assets/img/senders/firebase.svg"}
                                  activeStyles="border-orange-500 bg-orange-50/10"
                                  color="text-orange-500"
                                  bg="bg-orange-50"
                                  onClick={() => updateSetting(data.optionNames.otpMethod, 'firebase')}
                                />
                              </div>
                            </SettingCard>

                            {settings[data.optionNames.otpMethod] === 'whatsapp' && (
                              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                                <SettingCard className="p-0 overflow-hidden border-slate-100 shadow-none bg-slate-50/30">
                                  <ModernCardHeader
                                    title="WhatsApp Web Authentication"
                                    description="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="" />}
                                  />
                                  <div className="p-6 md:p-8">
                                    <WhatsAppAuthSettings
                                      settings={settings}
                                      updateSetting={updateSetting}
                                      optionNames={data.optionNames}
                                    />
                                  </div>
                                </SettingCard>
                              </motion.div>
                            )}

                            {settings[data.optionNames.otpMethod] === 'firebase' && (
                              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="space-y-4">
                                <SettingCard className="p-0 overflow-hidden border-slate-100 shadow-none bg-slate-50/30">
                                  <ModernCardHeader
                                    title="Firebase SMS Authentication"
                                    description="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="" />}
                                  />
                                  <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]">{msgs.firebase_tpl_label || "Manage Firebase SMS Templates"}</h5>
                                      <p className="text-[12px] text-slate-500 leading-relaxed font-medium max-w-xl">
                                        Firebase SMS messages are handled externally. To modify templates or manage costs, please visit your Firebase control panel.
                                      </p>
                                    </div>
                                    <a
                                      href="https://console.firebase.google.com/" target="_blank"
                                      className="shrink-0 px-6 py-2.5 bg-orange-600 hover:bg-orange-700 !text-white text-[12px] font-black rounded-[5px] transition-all flex items-center gap-2 shadow-none hover:shadow-lg hover:shadow-orange-100 active:scale-95"
                                      style={{ color: 'white' }}
                                    >
                                      Open Firebase Console
                                      <ExternalLink size={14} className="!text-white" style={{ color: 'white' }} />
                                    </a>
                                  </div>
                                  <div className="px-6 md:px-8 pb-8">
                                    <StatusMessage
                                      type={data.firebaseConfigured ? 'active' : 'warning'}
                                      message={data.firebaseConfigured ? "Firebase Account found. System is ready to route messages through Google gateway." : "<b>Firebase is not configured!</b> Please visit the Firebase Settings tab first."}
                                    />
                                  </div>
                                </SettingCard>
                              </motion.div>
                            )}
                          </div>
                        </motion.div>
                      )}
                    </AnimatePresence>
                  </div>
                </SettingCard>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <CompactSettingCard
                    title={t.show_phone_bar_global_label}
                    description="Display bar on all public pages."
                    icon={Zap}
                    checked={settings[data.optionNames.showPhoneBarGlobal] == 1}
                    disabled={settings[data.optionNames.showPhoneBar] != 1}
                    onChange={(val) => updateSetting(data.optionNames.showPhoneBarGlobal, val ? 1 : 0)}
                    statusMessage={getStatus('showPhoneBarGlobal')?.message}
                    statusType={getStatus('showPhoneBarGlobal')?.type}
                  />

                  <CompactSettingCard
                    title={t.lock_site_label}
                    description="Enforce mandatory verification."
                    icon={Lock}
                    checked={settings[data.optionNames.lockSite] == 1}
                    disabled={settings[data.optionNames.showPhoneBar] != 1}
                    onChange={(val) => updateSetting(data.optionNames.lockSite, val ? 1 : 0)}
                    statusMessage="<b>Security Note:</b> Locking the site restricts all frontend access until verified."
                    statusType="warning"
                  />
                </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>
    </div>
  </SettingsLayout>
  );
};

export default AuthenticationPagesSettings;
