import React, { useState } from 'react'
import {
  Smartphone,
  BookOpen,
  Zap,
  RotateCcw,
  Languages,
  BellRing,
  UserPlus,
  KeyRound,
  AlertCircle,
  Users,
  ShieldCheck,
  Activity,
  ShieldAlert,
  MessageSquare,
  FileCode,
  Settings,
  Search,
  X
} 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);
    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}${data.global.settingsRestUrl.includes('?') ? '&' : '?'}_=${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_campaigns_enabled': 'campaigns',
          'wawp_abandoned_carts_enabled': 'abandonedCarts',
          '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_checkout_otp_enabled': 'checkoutOtp',
          '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', 'checkoutOtp', '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%' };

  // Fallback if i18n is partially missing to prevent white page
  const pageTitle = "Dashboard"
  const 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) => true;
  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', 'abandonedCarts', 'campaigns', 'emailTemplates', 'multilang', 'subNotifs'] as (keyof typeof data.features)[]).some(k => !!data?.features?.[k]);
  const hasAuth = (['countryCode', 'otpLogin', 'signupOtp', 'checkoutOtp', '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 size={14} 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-9"
                      style={{
                        paddingLeft: data.rtl ? '16px' : '40px',
                        paddingRight: data.rtl ? '40px' : '16px'
                      }}
                      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 size={14} strokeWidth={2.5} />
                    </button>
                  </div>
                ) : (
                  <SecondaryButton
                    className="bg-white px-2.5 h-9 w-9 flex items-center justify-center border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/sbtn"
                    onClick={() => setIsSearchOpen(true)}
                  >
                    <Search size={16} strokeWidth={2.5} className="text-slate-500 group-hover/sbtn:text-[#004449] transition-colors" />
                  </SecondaryButton>
                )}

                <SecondaryButton className="bg-white w-full sm:w-auto h-9 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>
              </div>
            </div>
          </SettingsHeader>


          {/* 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>
                )}
                <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('featAbandonTitle', ''), t('featAbandonDesc', '')) || matchesSearch(t('featCampaignTitle', ''), t('featCampaignDesc', '')) || matchesSearch(t('emailTemplates', ''), t('emailTemplatesDesc', '')) || matchesSearch(t('featMultiTitle', ''), t('featMultiDesc', '')) || matchesSearch(t('featSubTitle', ''), t('featSubDesc', ''))) && (
            <FeatSection
              title="Engagement & Retention"
              description="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="https://help.wawp.net/en_US/whatsapp-chat-button/" settingsUrl={data.urls.chatWidget} t={t as unknown as Record<string, string>} />}
              {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="https://help.wawp.net/en_US/automated-notifications/" settingsUrl={data.urls.notifications} t={t as unknown as Record<string, string>} />}
              {hasFeature('abandonedCarts') && matchesSearch(t('featAbandonTitle', ''), t('featAbandonDesc', '')) && <FeatRow icon={RotateCcw} title={t('featAbandonTitle', 'Abandoned Carts')} desc={t('featAbandonDesc', '')} enabled={isEnabled('abandonedCarts')} allowed={isAllowed('abandonedCarts')} error={getError('abandonedCarts')} onToggle={() => toggle('abandonedCarts')} docs="https://help.wawp.net/en_US/abandoned-carts/" settingsUrl={data.urls.abandonedCarts} pluginLink={data.wooStatus.installed ? data.urls.wooActivate : data.urls.wooInstall} t={t as unknown as Record<string, string>} />}
              {hasFeature('campaigns') && matchesSearch(t('featCampaignTitle', ''), t('featCampaignDesc', '')) && <FeatRow icon={BookOpen} title={t('featCampaignTitle', 'Campaigns')} desc={t('featCampaignDesc', '')} enabled={isEnabled('campaigns')} allowed={isAllowed('campaigns')} error={getError('campaigns')} onToggle={() => toggle('campaigns')} docs="https://help.wawp.net/en_US/wawp-bulk-campaigns/" settingsUrl={data.urls.campaigns} t={t as unknown as Record<string, string>} />}
              {hasFeature('multilang') && matchesSearch(t('featMultiTitle', ''), t('featMultiDesc', '')) && <FeatRow icon={Languages} title={t('featMultiTitle', 'Multi-Language')} desc={t('featMultiDesc', '')} enabled={isEnabled('multilang')} allowed={isAllowed('multilang')} error={getError('multilang')} onToggle={() => toggle('multilang')} docs="https://help.wawp.net/en_US/wawp-plugin-dashboard/" settingsUrl={data.urls.notifications} t={t as unknown as Record<string, string>} />}
              {hasFeature('subNotifs') && matchesSearch(t('featSubTitle', ''), t('featSubDesc', '')) && <FeatRow icon={BellRing} title={t('featSubTitle', 'Subscription')} desc={t('featSubDesc', '')} enabled={isEnabled('subNotifs')} allowed={isAllowed('subNotifs')} error={getError('subNotifs')} onToggle={() => toggle('subNotifs')} docs="https://help.wawp.net/en_US/wawp-plugin-dashboard/" settingsUrl={data.urls.notifications} pluginLink={f('subNotifs').pluginLink} t={t as unknown as Record<string, string>} />}
            </FeatSection>
          )}

          {hasAuth && (matchesSearch(t('featCountryTitle', ''), t('featCountryDesc', '')) || matchesSearch(t('featLoginTitle', ''), t('featLoginDesc', '')) || matchesSearch(t('featSignupTitle', ''), t('featSignupDesc', '')) || matchesSearch(t('featCheckoutTitle', ''), t('featCheckoutDesc', '')) || matchesSearch(t('featPagesTitle', ''), t('featPagesDesc', '')) || matchesSearch(t('featRecaptchaTitle', ''), t('featRecaptchaDesc', ''))) && (
            <FeatSection
              title="Authentication & User Management"
              description="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="https://help.wawp.net/en_US/advanced-country-code/" settingsUrl={data.urls.phoneField} t={t as unknown as Record<string, string>} />}
              {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="https://help.wawp.net/en_US/passwordless-login/" settingsUrl={data.urls.otpLogin} t={t as unknown as Record<string, string>} />}
              {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="https://help.wawp.net/en_US/registration-form-builder/" settingsUrl={data.urls.registration} t={t as unknown as Record<string, string>} />}
              {matchesSearch(t('featCheckoutTitle', ''), t('featCheckoutDesc', '')) && <FeatRow icon={ShieldCheck} title={t('featCheckoutTitle', 'Checkout Verification')} desc={t('featCheckoutDesc', 'Reduce fake orders by verifying customer phone numbers during payment.')} enabled={isEnabled('checkoutOtp')} allowed={isAllowed('checkoutOtp')} error={getError('checkoutOtp')} onToggle={() => toggle('checkoutOtp')} docs="https://help.wawp.net/en_US/checkout-verification/" settingsUrl={data.urls.checkout} pluginLink={data.wooStatus.installed ? data.urls.wooActivate : data.urls.wooInstall} t={t as unknown as Record<string, string>} />}
              {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="https://help.wawp.net/en_US/authentication-pages/" settingsUrl={data.urls.pages} t={t as unknown as Record<string, string>} />}
              {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="https://help.wawp.net/en_US/google-recaptcha/" settingsUrl={data.urls.recaptcha} t={t as unknown as Record<string, string>} />}
            </FeatSection>
          )}
        </>
      </div>
    </SettingsLayout>
  )
}
