import React, { useState } from 'react'
import {
  Smartphone,
  BookOpen,
  Zap,

  UserPlus,
  KeyRound,
  AlertCircle,
  Users,
  ShieldCheck,
  Activity,
  ShieldAlert,
  MessageSquare,
  FileCode,
  Settings,
  Search,
  X,
  ExternalLink
} from 'lucide-react'
import { Switch } from './components/ui/switch'
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from './components/ui/tooltip'
import { toast } from "sonner"
import type { DashboardData } from './types'

import {
  SettingsLayout,
  SettingsHeader,
  SnapshotStat,
  FeatSection,
  FeatRow,
  SecondaryButton
} from './components/ui/settings-ui';

// ─── Dashboard ────────────────────────────────────────────────────────────────

export default function Dashboard({ data: initialData }: { data: DashboardData }) {
  const [data, setData] = useState<DashboardData>(initialData)
  const [searchQuery, setSearchQuery] = useState('')
  const [isSearchOpen, setIsSearchOpen] = useState(false)
  const searchRef = React.useRef<HTMLInputElement>(null)

  React.useEffect(() => {
    if (isSearchOpen && searchRef.current) {
      searchRef.current.focus();
    }
  }, [isSearchOpen]);

  const [prevInitialData, setPrevInitialData] = useState(initialData);
  const [savingItems, setSavingItems] = useState<Record<string, boolean>>({});
  if (initialData !== prevInitialData) {
    setPrevInitialData(initialData);
    if (JSON.stringify(initialData?.features) !== JSON.stringify(prevInitialData?.features)) {
      setData(initialData);
    }
  }

  const toggle = async (key: string) => {
    if (!data || savingItems[key]) return;
    const feat = data.features[key];
    const isActuallyEnabled = Number(feat.enabled) === 1 || feat.enabled === true;
    const next = isActuallyEnabled ? 0 : 1;

    setSavingItems(prev => ({ ...prev, [key]: true }));

    // Optimistic UI update
    setData(prev => prev ? {
      ...prev, features: { ...prev.features, [key]: { ...feat, enabled: next } }
    } : prev);

    try {
      const res = await fetch(`${data.global.settingsRestUrl}?_=${Date.now()}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': data.global.wpRestNonce
        },
        body: JSON.stringify({
          settings: {
            [feat.option]: next
          }
        })
      });

      const json = await res.json();

      if (json.success) {
        toast.success(data.i18n.successTitle || 'Success', {
          description: data.i18n.success
        });

        // Dispatch global refresh event with a small delay to allow transients to settle
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent('wawp-refresh-data', {
            detail: { section: 'dashboard' }
          }));
        }, 150);

        // Notify sidebar about section visibility
        const sidebarMapping: Record<string, string> = {
          'wawp_otp_enabled': 'otp',
          'wawp_chat_widget_enabled': 'chatWidget',
          'wawp_notifications_enabled': 'notifications',
          'wawp_system_info_enabled': 'systemInfo',
          'wawp_countrycode_enabled': 'phoneField',
          'wawp_google_recaptcha_enabled': 'recaptcha',
          'wawp_passwordless_login_enabled': 'otpLogin',
          'wawp_signup_enabled': 'signupOtp',
          'wawp_custom_pages_enabled': 'authPages',
          'wawp_unified_log_enabled': 'activityHub',
          'wawp_email_templates_enabled': 'emailTemplates'
        };

        const sidebarKey = sidebarMapping[feat.option];
        if (sidebarKey) {
          window.dispatchEvent(new CustomEvent('wawp-sections-updated', {
            detail: { [sidebarKey]: next === 1 }
          }));

          // If child OTP feature is enabled, ensure master OTP group is also shown in sidebar
          if (['otpLogin', 'signupOtp', 'customPages'].includes(sidebarKey) && next === 1) {
            window.dispatchEvent(new CustomEvent('wawp-sections-updated', {
              detail: { otp: true }
            }));
          }
        }
      } else {
        throw new Error(json.data || 'Action failed');
      }
    } catch (err) {
      // Revert on error
      setData(prev => prev ? {
        ...prev, features: { ...prev.features, [key]: { ...feat, enabled: isActuallyEnabled ? 1 : 0 } }
      } : prev);
      toast.error(data.i18n.errorTitle || 'Error', {
        description: (err as Error).message
      });
    } finally {
      setSavingItems(prev => ({ ...prev, [key]: false }));
    }
  };

  const t = React.useCallback((key: string, fallback: string = ''): string => {
    const val = (data?.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  }, [data.i18n]);
  const stats = data?.stats || { totalWpUsers: 0, usersWithPhone: 0, verified: 0, percentAdded: '0%', percentVerified: '0%' };

  // Build help URL: AR → help.wawp.net/ar/articles/..., EN → help.wawp.net/en/articles/...
  const docsUrl = (slug: string): string => {
    const lang = data.rtl ? 'ar' : 'en';
    return `https://help.wawp.net/${lang}/articles/${slug}`;
  };

  const translations = {
    labelPro: t('proVersion', 'PRO'),
    btnSettings: t('btnSettings', 'Settings'),
    btnUpgrade: t('btnUpgrade', 'Upgrade'),
    btnActivate: t('btnActivate', 'Activate'),
  };

  // Fallback if i18n is partially missing to prevent white page
  const pageTitle = t('pageTitle', 'Dashboard');
  const pageSubtitle = t('pageSubtitle', 'Manage your automated workflows, track delivery performance, and monitor system health in one centralized location.');

  if (!data) return null;
  const f = (key: string) => data?.features?.[key] || { enabled: false, allowed: false, option: '', error: undefined, pluginLink: undefined };
  const isEnabled = (key: string) => {
    const feat = f(key);
    return Number(feat.enabled) === 1 || feat.enabled === true;
  };
  const isAllowed = (key: string) => {
    const feat = f(key);
    return feat.allowed === true || Number(feat.allowed) === 1;
  };
  const getError = (key: string) => f(key).error as string | undefined;
  const hasFeature = (key: string) => !!data.features[key as keyof typeof data.features];

  const hasEngagement = (['chatWidget', 'notifications', 'emailTemplates'] as (keyof typeof data.features)[]).some(k => !!data?.features?.[k]);
  const hasAuth = (['countryCode', 'otpLogin', 'signupOtp', 'customPages', 'recaptcha'] as (keyof typeof data.features)[]).some(k => !!data?.features?.[k]);

  const matchesSearch = (title: string = '', desc: string = '') => {
    if (!searchQuery) return true;
    const q = searchQuery.toLowerCase();
    return title.toLowerCase().includes(q) || desc.toLowerCase().includes(q);
  };

  return (
    <SettingsLayout>
      <div className="max-w-7xl mx-auto space-y-8">

          <>
            {/* WooCommerce Missing Global Notice */}
            <SettingsHeader
              title={pageTitle}
              description={pageSubtitle}
            >
              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full sm:w-auto">
                <div className="flex items-center gap-2 w-full sm:w-auto justify-end">
                  {isSearchOpen ? (
                    <div className="relative group/search w-full sm:w-auto animate-in fade-in slide-in-from-right-2 duration-300">
                      <div
                        className="absolute inset-y-0 flex items-center pointer-events-none text-slate-400 group-focus-within/search:text-[#004449] transition-colors"
                        style={{ [data.rtl ? 'right' : 'left']: '12px' }}
                      >
                        <Search className="w-3.5 h-3.5" strokeWidth={2.5} />
                      </div>
                      <input
                        ref={searchRef}
                        type="text"
                        placeholder={t('search', "Search features...")}
                        className="w-full sm:w-[240px] bg-white border border-[#dcdcde] rounded-[5px] text-[12px] font-medium focus:ring-2 focus:ring-[#004449]/10 focus:border-[#004449]/50 transition-all outline-none h-8"
                        style={{
                          paddingLeft: '40px',
                          paddingRight: '40px'
                        }}
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Escape') {
                            setSearchQuery('');
                            setIsSearchOpen(false);
                          }
                        }}
                      />
                      <button
                        onClick={() => { setSearchQuery(''); setIsSearchOpen(false); }}
                        className="absolute inset-y-0 flex items-center text-slate-400 hover:text-slate-600 p-1"
                        style={{ [data.rtl ? 'left' : 'right']: '8px' }}
                      >
                        <X className="w-3.5 h-3.5" strokeWidth={2.5} />
                      </button>
                    </div>
                  ) : (
                    <SecondaryButton
                      size="icon"
                      className="bg-white border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/sbtn"
                      onClick={() => setIsSearchOpen(true)}
                    >
                      <Search className="w-4 h-4 text-slate-500 group-hover/sbtn:text-[#004449] transition-colors" strokeWidth={2.5} />
                    </SecondaryButton>
                  )}

                  <SecondaryButton
                    size="md"
                    className="bg-white w-full sm:w-auto border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/vbtn"
                    onClick={() => window.open(data.urls.usersAdmin, '_blank')}
                  >
                    <Users className="w-3.5 h-3.5 me-1.5 text-slate-500 group-hover/vbtn:text-[#004449] transition-colors" />
                    {t('viewAllUsers', 'View Users')}
                  </SecondaryButton>

                  <SecondaryButton
                    size="icon"
                    className="bg-white border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/dbtn"
                    onClick={() => window.open(docsUrl('wawp-plugin-dashboard'), '_blank')}
                    title={data.rtl ? 'دليل لوحة التحكم' : 'Dashboard Guide'}
                  >
                    <BookOpen className="w-4 h-4 text-slate-500 group-hover/dbtn:text-[#004449] transition-colors" strokeWidth={2} />
                  </SecondaryButton>
                </div>
              </div>
            </SettingsHeader>


            {/* Free Edition: Upgrade / Features Comparison Notice */}
            <div className="bg-gradient-to-r from-emerald-50 via-teal-50/50 to-blue-50 border border-emerald-100/80 rounded-xl p-5 flex flex-col sm:flex-row items-center justify-between gap-4 shadow-[0_1px_3px_rgba(0,0,0,0.02)]">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 rounded-lg bg-emerald-500/10 flex items-center justify-center text-emerald-600 shrink-0">
                  <Zap className="w-5 h-5 animate-pulse" />
                </div>
                <div>
                  <h4 className="text-sm font-bold text-slate-800" style={{ margin: 0, padding: 0 }}>
                    {data.rtl ? "أطلق القوة الكاملة لـ Wawp (برو)" : "Unlock Wawp Full Power & Features"}
                  </h4>
                  <p className="text-xs text-slate-600 mt-1" style={{ margin: '4px 0 0 0', padding: 0 }}>
                    {data.rtl
                      ? "اكتشف الفروق بين إصدارات الإضافة المختلفة وقارن الميزات لتفعيل الأتمتة المتقدمة لمتجرك."
                      : "Explore differences between plugin editions and compare advanced features to grow your WooCommerce store."}
                  </p>
                </div>
              </div>
              <a
                href={`https://help.wawp.net/${data.rtl ? 'ar' : 'en'}/labels`}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center justify-center gap-1.5 px-4.5 py-2 rounded-lg bg-[#004449] hover:bg-[#003337] text-white font-bold text-[12px] shadow-sm hover:shadow transition-all duration-200 cursor-pointer shrink-0"
                style={{ color: '#ffffff' }}
              >
                <span style={{ color: '#ffffff' }}>{data.rtl ? "مقارنة الميزات والإصدارات" : "Compare Features & Editions"}</span>
                <ExternalLink className="w-3.5 h-3.5" style={{ color: '#ffffff' }} />
              </a>
            </div>

            {/* User Stats Snapshot */}
            <FeatSection
              title={t('snapshotTitle', 'Snapshot')}
              description={t('snapshotSubtitle', 'Overview of your users')}
              icon={Activity}
              gridCols="sm:grid-cols-3"
            >
              <SnapshotStat
                value={stats.totalWpUsers.toString()}
                label={t('allUsers', "All Users")}
                sub={t('allUsersSub', "Total WordPress accounts.")}
                badge={t('badgeDb', "DB")}
                badgeVariant="secondary"
                percent={100}
                barColor="bg-slate-400"
                icon={Users}
              />
              <SnapshotStat
                value={stats.usersWithPhone.toString()}
                label={t('phoneAdded', 'Phone Added')} sub={t('phoneAddedSub', 'Users with phone number')}
                badge={t('badgeAll', 'ALL')} badgeVariant="secondary"
                percent={stats.percentAdded} barColor="bg-blue-500"
                icon={Smartphone}
              />
              <SnapshotStat
                value={stats.verified.toString()}
                label={t('verifiedLabel', 'Verified')} sub={t('verifiedSub', 'Identity verified')}
                badge={t('badgeVerified', 'OK')} badgeVariant="success"
                percent={stats.percentVerified} barColor="bg-green-500"
                percentText={stats.percentVerified}
                valueClass="text-green-600"
                icon={ShieldCheck}
              />

              {/* System Information Switch */}
              <div className="sm:col-span-3 pt-6 mt-2 border-t border-slate-100 flex items-center justify-between group">
                <div className="flex items-center gap-3">
                  <div className="h-9 w-9 rounded-lg bg-slate-50 flex items-center justify-center text-slate-400 group-hover:text-[#004449] transition-colors">
                    <Activity size={18} />
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-[13px] font-bold text-slate-700">{t('featSysInfoTitle', 'System Info')}</span>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <button className="text-slate-300 hover:text-slate-400 transition-colors">
                          <AlertCircle size={14} />
                        </button>
                      </TooltipTrigger>
                      <TooltipContent side="top" className="max-w-[280px] bg-slate-900 text-white p-3 rounded-lg shadow-xl">
                        {t('featSysInfoDesc', 'Monitor your server health and WordPress environment in real-time to ensure seamless performance for all automation tasks.')}
                      </TooltipContent>
                    </Tooltip>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  {isEnabled('systemInfo') && (
                    <SecondaryButton
                      className="border-slate-200 text-slate-600 hover:bg-slate-50 shadow-none"
                      onClick={() => window.dispatchEvent(new CustomEvent('wawp-navigate', { detail: 'system_info' }))}
                    >
                      <Settings className="w-3 h-3 me-1.5" />
                      {t('btnSettings', 'Settings')}
                    </SecondaryButton>
                  )}
                  <button
                    type="button"
                    className="h-8 w-8 rounded-[6px] flex items-center justify-center text-slate-400 hover:text-slate-700 bg-slate-50 hover:bg-slate-100 border border-slate-200/50 transition-all active:scale-95"
                    onClick={() => window.open(docsUrl('wawp-system-status'), '_blank')}
                    title={data.rtl ? 'دليل حالة النظام' : 'System Status Guide'}
                  >
                    <ExternalLink size={13} />
                  </button>
                  <Switch
                    checked={isEnabled('systemInfo')}
                    onCheckedChange={() => toggle('systemInfo')}
                  />
                </div>
              </div>
            </FeatSection>

            {/* Feature Sections */}


            {hasEngagement && (matchesSearch(t('featChatTitle', ''), t('featChatDesc', '')) || matchesSearch("Dashboard", "Centralized command center") || matchesSearch(t('emailTemplates', ''), t('emailTemplatesDesc', '')) || matchesSearch(t('featMultiTitle', ''), t('featMultiDesc', '')) || matchesSearch(t('featSubTitle', ''), t('featSubDesc', ''))) && (
              <FeatSection
                title={t('sectionEngagement', 'Engagement & Retention')}
                description={t('sectionEngagementDesc', 'Advanced communication tools to increase customer life-time value.')}
                badge={t('badgeConnect', 'Connect')}
                icon={Zap}
              >
                {hasFeature('chatWidget') && matchesSearch(t('featChatTitle', ''), t('featChatDesc', '')) && <FeatRow icon={MessageSquare} title={t('featChatTitle', 'Chat Widget')} desc={t('featChatDesc', '')} enabled={isEnabled('chatWidget')} allowed={isAllowed('chatWidget')} error={getError('chatWidget')} onToggle={() => toggle('chatWidget')} docs={docsUrl('whatsapp-chat-button')} settingsUrl={data.urls.chatWidget} upgradeUrl={data.urls.pricing} t={translations} />}
                {hasFeature('notifications') && matchesSearch(t('featNotifTitle', ''), t('featNotifDesc', '')) && <FeatRow icon={Zap} title={t('featNotifTitle', 'Notifications')} desc={t('featNotifDesc', '')} enabled={isEnabled('notifications')} allowed={isAllowed('notifications')} error={getError('notifications')} onToggle={() => toggle('notifications')} docs={docsUrl('automated-notifications')} settingsUrl={data.urls.notifications} upgradeUrl={data.urls.pricing} t={translations} />}

              </FeatSection>
            )}

            {hasAuth && (matchesSearch(t('featCountryTitle', ''), t('featCountryDesc', '')) || matchesSearch(t('featLoginTitle', ''), t('featLoginDesc', '')) || matchesSearch(t('featSignupTitle', ''), t('featSignupDesc', '')) || matchesSearch(t('featPagesTitle', ''), t('featPagesDesc', '')) || matchesSearch(t('featRecaptchaTitle', ''), t('featRecaptchaDesc', ''))) && (
              <FeatSection
                title={t('sectionAuth', 'Authentication & User Management')}
                description={t('sectionAuthDesc', 'Secure and streamline your user onboarding with WhatsApp-powered identity flows.')}
                badge={t('badgeSecurity', 'Security')}
                icon={ShieldAlert}
              >
                {matchesSearch(t('featCountryTitle', ''), t('featCountryDesc', '')) && <FeatRow icon={Smartphone} title={t('featCountryTitle', 'Country Code Management')} desc={t('featCountryDesc', 'Automatically detect and validate user country codes.')} enabled={isEnabled('countryCode')} allowed={isAllowed('countryCode')} error={getError('countryCode')} onToggle={() => toggle('countryCode')} docs={docsUrl('advanced-country-code')} settingsUrl={data.urls.phoneField} upgradeUrl={data.urls.pricing} t={translations} />}
                {matchesSearch(t('featLoginTitle', ''), t('featLoginDesc', '')) && <FeatRow icon={KeyRound} title={t('featLoginTitle', 'Passwordless Login')} desc={t('featLoginDesc', 'Allow customers to log in via WhatsApp OTP instead of passwords.')} enabled={isEnabled('otpLogin')} allowed={isAllowed('otpLogin')} error={getError('otpLogin')} onToggle={() => toggle('otpLogin')} docs={docsUrl('passwordless-login')} settingsUrl={data.urls.otpLogin} upgradeUrl={data.urls.pricing} t={translations} />}
                {matchesSearch(t('featSignupTitle', ''), t('featSignupDesc', '')) && <FeatRow icon={UserPlus} title={t('featSignupTitle', 'Advanced Registration')} desc={t('featSignupDesc', 'Streamline user registration with a form builder and phone verification.')} enabled={isEnabled('signupOtp')} allowed={isAllowed('signupOtp')} error={getError('signupOtp')} onToggle={() => toggle('signupOtp')} docs={docsUrl('registration-form')} settingsUrl={data.urls.registration} upgradeUrl={data.urls.pricing} t={translations} />}
                {matchesSearch(t('featPagesTitle', ''), t('featPagesDesc', '')) && <FeatRow icon={FileCode} title={t('featPagesTitle', 'Custom Auth Pages')} desc={t('featPagesDesc', 'Design fully branded login and registration pages.')} enabled={isEnabled('customPages')} allowed={isAllowed('customPages')} error={getError('customPages')} onToggle={() => toggle('customPages')} docs={docsUrl('about-authentication-pages-settings')} settingsUrl={data.urls.pages} upgradeUrl={data.urls.pricing} t={translations} />}
                {matchesSearch(t('featRecaptchaTitle', ''), t('featRecaptchaDesc', '')) && <FeatRow icon={ShieldAlert} title={t('featRecaptchaTitle', 'reCAPTCHA Protection')} desc={t('featRecaptchaDesc', 'Protect your site from bots and spam with advanced integration.')} enabled={isEnabled('recaptcha')} allowed={isAllowed('recaptcha')} error={getError('recaptcha')} onToggle={() => toggle('recaptcha')} docs={docsUrl('google-recaptcha')} settingsUrl={data.urls.recaptcha} upgradeUrl={data.urls.pricing} t={translations} />}
              </FeatSection>
            )}
          </>
      </div>
    </SettingsLayout>
  )
}
