import React, { useState } from 'react';
import { toast } from 'sonner';
import {
  ShieldBan,
  Cable,
  LayoutDashboard,
  ShieldCheck,
  History,
  FileText,
  MessagesSquare,
  BookOpen,
  Zap,
  ExternalLink
} from 'lucide-react';

import { useUrlTabs } from './hooks/use-url-tabs';
import type { DashboardData } from './types';
import {
  SettingsLayout,
  FeatSection,
  FeatRow,
  SettingsHeader,
  FlatTabs,
  SecondaryButton
} from './components/ui/settings-ui';

export default function Senders({ data: dashboardData }: { data: DashboardData }) {
  const t = React.useCallback((key: string, fallback: string = ''): string => {
    const val = (dashboardData?.i18n as Record<string, unknown>)?.[key];
    return typeof val === 'string' ? val : fallback;
  }, [dashboardData.i18n]);

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

  const senderData = (dashboardData?.sendersData as {
    enabled: Record<string, number>;
    allowed: Record<string, boolean>;
  }) || {
    enabled: { email: 1, wa: 1, block: 1 },
    allowed: { email: true, wa: true, block: true }
  };

  const [enabled, setEnabled] = useState(senderData.enabled);
  const [features, setFeatures] = useState(dashboardData.features || {});
  const [activeTab, setActiveTab] = useUrlTabs('overview');

  const [prevEnabledProp, setPrevEnabledProp] = useState(senderData.enabled);
  if (senderData.enabled !== prevEnabledProp) {
    setPrevEnabledProp(senderData.enabled);
    if (JSON.stringify(senderData.enabled) !== JSON.stringify(prevEnabledProp)) {
      setEnabled(senderData.enabled);
    }
  }

  const [prevFeaturesProp, setPrevFeaturesProp] = useState(dashboardData.features);
  if (dashboardData.features !== prevFeaturesProp) {
    setPrevFeaturesProp(dashboardData.features);
    if (JSON.stringify(dashboardData.features) !== JSON.stringify(prevFeaturesProp)) {
      setFeatures(dashboardData.features || {});
    }
  }

  const handleToggle = async (key: string, value: boolean) => {
    const newState = { ...enabled, [key]: value ? 1 : 0 };
    setEnabled(newState);

    try {
      const response = await fetch(dashboardData.global.settingsRestUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          settings: {
            wawp_senders_enabled: newState
          }
        })
      });
      const result = await response.json();
      if (result.success) {
        toast.success(result.message || t('toastSaved', 'Settings saved successfully'));
        window.dispatchEvent(new CustomEvent('wawp-senders-updated', { detail: newState }));
      } else {
        toast.error(result.message || t('toastFailed', 'Failed to save settings'));
        setEnabled(enabled);
      }
    } catch (e: unknown) {
      console.error('Sender save error:', e);
      toast.error(t('toastNetwork', 'Network error'));
      setEnabled(enabled);
    }
  };

  const handleFeatureToggle = async (featureKey: string) => {
    const feature = features[featureKey];
    if (!feature) return;

    const newValue = !feature.enabled;

    setFeatures((prev) => ({
      ...prev,
      [featureKey]: { ...feature, enabled: newValue }
    }));

    try {
      const response = await fetch(dashboardData.global.settingsRestUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': dashboardData.global.wpRestNonce
        },
        body: JSON.stringify({
          settings: {
            [feature.option]: newValue ? 1 : 0
          }
        })
      });

      const result = await response.json();
      if (result.success) {
        toast.success(result.message || t('toastUpdated', 'Updated successfully'));
        const sidebarMapping: Record<string, string> = {
          'wawp_custom_pages_enabled': 'authPages',
          'wawp_unified_log_enabled': 'activityHub',
          'wawp_enable_tracking_ids': 'trackingIds',
          'wawp_email_templates_enabled': 'emailTemplates'
        };
        const sidebarKey = sidebarMapping[feature.option];
        if (sidebarKey) {
          window.dispatchEvent(new CustomEvent('wawp-sections-updated', {
            detail: { [sidebarKey]: newValue }
          }));
        }
      } else {
        toast.error(result.message || t('toastError', 'An error occurred'));
        setFeatures(features);
      }
    } catch {
      toast.error(t('toastNetwork', 'Network error'));
      setFeatures(features);
    }
  };


  const isRTL = !!dashboardData.rtl;

  const tabs = [
    { id: 'overview', label: t('tabOverview', 'Senders Overview'), icon: LayoutDashboard },
    { id: 'tools', label: t('tabTools', 'Messaging Tools'), icon: MessagesSquare }
  ];

  interface SenderItem {
    id: string;
    name: string;
    desc: string;
    iconUrl: string;
    settingsUrl: string;
    allowed: boolean;
    docs: string;
    error?: string;
  }

  const sendersList: SenderItem[] = [
    {
      id: 'wa',
      name: t('waName', 'WhatsApp Web'),
      desc: t('waDesc', 'Connect your personal WhatsApp for automated notifications and OTPs.'),
      iconUrl: `${dashboardData?.global?.pluginUrl || ''}assets/img/senders/whatsapp.svg`,
      settingsUrl: 'admin.php?page=wawp&wawp_section=whatsapp-web-sender',
      allowed: senderData.allowed.wa,
      docs: `https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-connect-whatsapp-web`
    },
    {
      id: 'email',
      name: t('emailName', 'Email (SMTP)'),
      desc: t('emailDesc', 'Send transactional emails via your custom SMTP server for reliability.'),
      iconUrl: `${dashboardData?.global?.pluginUrl || ''}assets/img/senders/gmail.svg`,
      settingsUrl: 'admin.php?page=wawp&wawp_section=smtp-sender',
      allowed: senderData.allowed.email,
      docs: `https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-setup-smtp-email`
    }
  ];

  return (
    <SettingsLayout>
      <SettingsHeader
        title={t('sendersTitle', "Senders & Messaging")}
        description={t('sendersSubtitle', "Configure your communication gateways and optimize your messaging engagement.")}
      >
        <SecondaryButton
          size="icon"
          className="bg-white border-[#dcdcde] hover:border-[#004449]/30 hover:text-[#004449] group/dbtn shrink-0"
          onClick={() => window.open(
            activeTab === 'tools'
              ? `https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/about-messaging-tools`
              : `https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/sender-settings-tutorial`,
            '_blank'
          )}
          title={
            activeTab === 'tools'
              ? (dashboardData?.rtl ? 'دليل أدوات المراسلة' : 'Messaging Tools Guide')
              : (dashboardData?.rtl ? 'دليل إعدادات مرسلي الرسائل' : 'Sender Settings Guide')
          }
        >
          <BookOpen className="w-4 h-4 text-slate-500 group-hover/dbtn:text-[#004449] transition-colors" strokeWidth={2} />
        </SecondaryButton>
      </SettingsHeader>

      <FlatTabs
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />

      {/* Pro Version Senders 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)] mb-6 animate-in fade-in duration-300">
        <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 }}>
              {isRTL ? "المزيد من بوابات الإرسال وتتبع حالة القراءة (برو)" : "More Gateways & Read Tracking (Pro)"}
            </h4>
            <p className="text-xs text-slate-600 mt-1" style={{ margin: '4px 0 0 0', padding: 0 }}>
              {isRTL
                ? "قم بترقية حسابك لتوصيل Firebase SMS و Meta WhatsApp Cloud API، وتتبع حالة قراءة الرسائل لمعرفة ما إذا كانت قد قُرئت أم لا!"
                : "Upgrade to Pro to connect Firebase SMS, Meta WhatsApp Cloud API, and track message read status (know if messages were read or not)!"}
            </p>
          </div>
        </div>
        <a
          href={dashboardData.urls?.pricing || "https://wawp.net/en/pricing"}
          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' }}>{isRTL ? "شاهد الأسعار" : "View Pricing"}</span>
          <ExternalLink className="w-3.5 h-3.5" style={{ color: '#ffffff' }} />
        </a>
      </div>

      <div className="space-y-6">
        {activeTab === 'overview' && (
          <div className="animate-in fade-in slide-in-from-bottom-2 duration-300">
            <FeatSection
              title={t('activeSenders', 'Active Senders')}
              description={t('activeSendersDesc', 'Manage your primary communication channels and their individual settings.')}
              icon={Cable}
            >
              {sendersList
                .map((sender) => (
                  <FeatRow
                    key={sender.id}
                    icon={sender.iconUrl ? () => <img src={sender.iconUrl} className="w-6 h-6 object-contain" alt="" /> : Cable}
                    title={sender.name}
                    desc={sender.desc}
                    enabled={!!enabled[sender.id as keyof typeof enabled]}
                    allowed={sender.allowed}
                    error={sender.error}
                    onToggle={() => handleToggle(sender.id, !enabled[sender.id])}
                    settingsUrl={sender.settingsUrl}
                    docs={sender.docs}
                    upgradeUrl={dashboardData.urls.pricing}
                    t={translations}
                  />
                ))}
            </FeatSection>
          </div>
        )}

        {activeTab === 'tools' && (
          <div className="animate-in fade-in slide-in-from-bottom-2 duration-300">
            <FeatSection
              title={t('messagingTools', 'Messaging Tools & Engagement')}
              description={t('messagingToolsDesc', 'Optimize your message delivery, tracking, and professional appearance.')}
              icon={ShieldCheck}
            >
              <FeatRow
                icon={ShieldBan}
                title={t('blockManagerName', 'Block Manager')}
                desc={t('blockManagerDesc', 'Easily manage and block specific phone numbers from receiving automated messages.')}
                enabled={!!enabled.block}
                allowed={senderData.allowed.block}
                onToggle={() => handleToggle('block', !enabled.block)}
                settingsUrl="admin.php?page=wawp&wawp_section=block-manager"
                docs={`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/how-to-block-whatsapp-numbers`}
                upgradeUrl={dashboardData.urls.pricing}
                t={translations}
              />

              {features.trackingIds && (
                <FeatRow
                  icon={ShieldCheck}
                  title={t('trackingIdsName', 'Unique Message IDs')}
                  desc={t('trackingIdsDesc', 'Append unique tracking IDs to every message for better analytics and delivery monitoring.')}
                  enabled={!!features.trackingIds.enabled}
                  allowed={features.trackingIds.allowed}
                  onToggle={() => handleFeatureToggle('trackingIds')}
                  docs={`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/unique-message-ids`}
                  upgradeUrl={dashboardData.urls.pricing}
                  t={translations}
                />
              )}

              {features.activityHub && (
                <FeatRow
                  icon={History}
                  title={t('activityHubName', 'Activity Hub')}
                  desc={t('activityHubDesc', 'Real-time logging of all automated interactions and system events for debugging and tracking.')}
                  enabled={!!features.activityHub.enabled}
                  allowed={features.activityHub.allowed}
                  onToggle={() => handleFeatureToggle('activityHub')}
                  settingsUrl="admin.php?page=wawp&wawp_section=activity_hub"
                  docs={`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/activity-hub`}
                  upgradeUrl={dashboardData.urls.pricing}
                  t={translations}
                />
              )}

              {features.emailTemplates && (
                <FeatRow
                  icon={FileText}
                  title={t('emailTemplatesName', 'Email Templates')}
                  desc={t('emailTemplatesDesc', 'Use a drag-and-drop builder to create professional, high-converting email communications.')}
                  enabled={!!features.emailTemplates.enabled}
                  allowed={features.emailTemplates.allowed}
                  onToggle={() => handleFeatureToggle('emailTemplates')}
                  settingsUrl="admin.php?page=wawp&wawp_section=email_templates"
                  docs={`https://help.wawp.net/${dashboardData?.rtl ? 'ar' : 'en'}/articles/email-templates`}
                  upgradeUrl={dashboardData.urls.pricing}
                  t={translations}
                />
              )}


            </FeatSection>
          </div>
        )}
      </div>
    </SettingsLayout>
  );
}
