import React, { useState } from 'react';
import type { DashboardData, ConnectorData } from './types';
import {
  RefreshCcw, LogOut,
  ArrowRight, Clock, Zap, Globe, Crown,
  Sparkles, Star, ShieldCheck, Shield, MessageSquare, Cable, Activity, FileCode, Smartphone,
  UserPlus, Bell, Mail, User
} from 'lucide-react';
import { OverloadAlert, NotActiveAlert, BlockedAlert } from './components/StatusAlerts';
import { CardContent, CardFooter } from './components/ui/card';
import { Switch } from './components/ui/switch';
import { Badge } from './components/ui/badge';

import { toast } from "sonner";
import { motion, AnimatePresence } from "framer-motion";
import {
  SettingsLayout,
  SettingsHeader,
  ModernCardHeader,
  SettingCard,
  SuccessButton,
  SecondaryButton
} from './components/ui/settings-ui';

const Connector: React.FC<{ data: DashboardData }> = ({ data: rootData }) => {
  const data = rootData?.connector as ConnectorData;
  const i18n = (rootData?.i18n || {}) as Record<string, string>;
  const rtl = rootData?.rtl || false;

  const [loading, setLoading] = useState(false);
  const [guestLoading, setGuestLoading] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [shareDiagnostics, setShareDiagnostics] = useState(data?.share_diagnostics || false);

  React.useEffect(() => {
    const timer = setTimeout(() => {
      setShareDiagnostics(data?.share_diagnostics || false);
    }, 0);
    return () => clearTimeout(timer);
  }, [data]);

  const handleRefresh = () => {
    setLoading(true);
    fetch(`${rootData?.global?.apiRestUrl}/connector/refresh`, {
      method: 'POST',
      headers: {
        'X-WP-Nonce': rootData?.global?.wpRestNonce
      }
    })
      .then((res: Response) => res.json())
      .then((response: { success: boolean }) => {
        if (response.success) {
          const url = new URL(window.location.href);
          url.searchParams.set('refresh_ts', new Date().getTime().toString());
          window.location.href = url.toString();
        } else {
          toast.error(i18n.errorOccurred || 'Refresh failed');
        }
      })
      .finally(() => setLoading(false));
  };

  const handleGuestLogin = () => {
    setGuestLoading(true);
    fetch(`${rootData?.global?.apiRestUrl}/connector/guest-login`, {
      method: 'POST',
      headers: {
        'X-WP-Nonce': rootData?.global?.wpRestNonce
      }
    })
      .then((res: Response) => res.json())
      .then((response: { success: boolean; message?: string }) => {
        if (response.success) {
          toast.success(response.message || 'Guest mode activated');
          setTimeout(() => {
            window.location.reload();
          }, 1000);
        } else {
          toast.error(response.message || 'Guest login failed');
        }
      })
      .catch(() => toast.error('An error occurred during guest login'))
      .finally(() => setGuestLoading(false));
  };




  const handleSave = React.useCallback(async (silent = true) => {
    setSaveStatus('saving');

    const globalData = rootData.global || {};
    const restUrl = globalData.settingsRestUrl || '';
    const wpNonce = globalData.wpRestNonce || '';

    try {
      const response = await fetch(restUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpNonce
        },
        body: JSON.stringify({
          settings: {
            wawp_share_diagnostic_data: shareDiagnostics ? 1 : 0
          }
        })
      });

      if (response.ok) {
        setHasUnsavedChanges(false);
        setSaveStatus('saved');
        window.dispatchEvent(new CustomEvent('wawp-refresh-data'));
        if (!silent) toast.success('Settings saved');
        setTimeout(() => setSaveStatus('idle'), 3000);
      } else {
        setSaveStatus('error');
      }
    } catch {
      setSaveStatus('error');
    }
  }, [rootData, shareDiagnostics]);

  React.useEffect(() => {
    if (!hasUnsavedChanges) return;
    const timer = setTimeout(() => handleSave(), 1500);
    return () => clearTimeout(timer);
  }, [shareDiagnostics, hasUnsavedChanges, handleSave]);

  const handleToggleDiagnostics = (enabled: boolean) => {
    setShareDiagnostics(enabled);
    setHasUnsavedChanges(true);
  };


  if (!data) return null;

  if (!data.connected || !data.is_sso) {
    return (
      <div className="w-full flex flex-col p-8 sm:p-12 items-center" dir={rtl ? 'rtl' : 'ltr'}>
        <div className="w-full max-w-7xl flex flex-col md:flex-row border border-slate-200 rounded-[5px] overflow-hidden bg-white min-h-[600px] shadow-none">
          <div className="flex-[1.4] bg-white flex flex-col border-b md:border-b-0 md:border-r border-slate-100 text-left">
            <ModernCardHeader
              icon={Sparkles}
              title="Get Started for Free"
              description="Connect your WordPress site with WAWP to unlock premium automation features."
              className="bg-slate-50/30 lg:px-12"
            />

            <div className="p-10 lg:p-12">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-y-10 gap-x-12">
                {[
                  { label: 'WhatsApp Web Sender', icon: MessageSquare, iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", color: 'text-emerald-500', desc: 'Direct message dispatch' },
                  { label: 'Email SMTP & Templates', icon: Mail, iconPath: (rootData.global?.pluginUrl || '') + "assets/img/senders/gmail.svg", color: 'text-orange-600', desc: 'Secure email delivery' },
                  { label: 'WhatsApp Chat Button', icon: MessageSquare, color: 'text-emerald-500', desc: 'Direct floating widget' },
                  { label: 'Registration Builder', icon: UserPlus, color: 'text-blue-500', desc: 'Custom signup forms' },
                  { label: 'Passwordless OTP Login', icon: Shield, color: 'text-amber-500', desc: 'Secured authentication' },
                  { label: 'System Diagnostics', icon: Activity, color: 'text-indigo-500', desc: 'Real-time performance' },
                  { label: 'Sender Management', icon: Cable, color: 'text-violet-500', desc: 'Connect multiple channels' },
                  { label: 'Free Message Quota', icon: Zap, color: 'text-orange-600', desc: 'Start sending instantly' },
                  { label: 'Cloud Synchronization', icon: Globe, color: 'text-sky-500', desc: 'Secure data mirroring' },
                  { label: 'Phone Field Formatting', icon: Smartphone, color: 'text-emerald-600', desc: 'Automatic country codes' },
                  { label: 'Order Alerts & Setup', icon: Bell, color: 'text-blue-600', desc: 'Instant status updates' },
                  { label: 'Real-time Entry Logs', icon: FileCode, color: 'text-rose-600', desc: 'Monitor message status' }
                ].map((f, i) => (
                  <div key={i} className="flex items-start gap-4 transition-all group">
                    <div className={`w-10 h-10 rounded-xl ${f.color.replace('text-', 'bg-')}/10 border ${f.color.replace('text-', 'border-')}/10 flex items-center justify-center shrink-0 mt-0.5`}>
                      {f.iconPath ? (
                        <img src={f.iconPath} className="w-5 h-5 object-contain" alt="" />
                      ) : (
                        <f.icon className={`w-5 h-5 ${f.color}`} />
                      )}
                    </div>
                    <div className="flex flex-col">
                      <span className="text-[14px] font-bold text-slate-700 tracking-tight group-hover:text-[#004449] transition-colors">{f.label}</span>
                      <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-widest leading-tight mt-1">{f.desc}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="flex-1 flex flex-col bg-white">
            <ModernCardHeader
              icon={ShieldCheck}
              title="Connect Your Account"
              description="Securely authenticate with Wawp to unlock synchronization."
              className="bg-slate-50/30 lg:px-12 border-l-0"
            />

            <div className="flex-1 p-10 lg:p-12 flex flex-col items-center justify-center text-center space-y-10 relative overflow-hidden">
              <div className="w-24 h-24 bg-slate-50 rounded-[1.8rem] flex items-center justify-center relative border border-slate-100">
                <div className="absolute inset-0 rounded-[1.8rem] border border-dashed border-slate-200 animate-[spin_30s_linear_infinite]" />
                <ShieldCheck className="w-12 h-12 text-[#004449]" />
              </div>

              <div className="w-full max-w-sm space-y-4 relative">
                <SuccessButton
                  onClick={() => window.location.href = data.login_url}
                  className="w-full !text-white shadow-none group"
                >
                  Authenticate Now
                  <ArrowRight className={`w-4 h-4 transition-transform group-hover:translate-x-1 ${rtl ? 'rotate-180 group-hover:-translate-x-1' : ''}`} />
                </SuccessButton>

                <SecondaryButton
                  onClick={handleGuestLogin}
                  disabled={guestLoading}
                  loading={guestLoading}
                  className="w-full border-slate-200 text-slate-600 hover:bg-slate-50 transition-all shadow-none"
                  icon={guestLoading ? undefined : User}
                >
                  Login as Guest
                </SecondaryButton>

                <div className="rounded-2xl border border-slate-100 overflow-hidden bg-slate-50/30">
                  <ModernCardHeader
                    icon={Activity}
                    title={i18n.shareDiagnostics}
                    description={i18n.shareDiagnosticsDesc}
                    className="border-none bg-transparent !px-5 !pt-5 !pb-3"
                    rightAction={
                      <Switch
                        checked={shareDiagnostics}
                        onCheckedChange={handleToggleDiagnostics}
                      />
                    }
                  />
                </div>

                <div className="flex flex-col items-center gap-2">
                  <p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest opacity-60">Need a new account?</p>
                  <div className="flex items-center gap-1.5 grayscale opacity-70 hover:grayscale-0 hover:opacity-100 transition-all">
                    <a
                      href="https://app.wawp.net/signup"
                      className="text-slate-500 font-bold text-[12px] h-auto p-0 hover:text-[#004449] no-underline hover:underline transition-all"
                    >
                      Create account
                    </a>
                    <span className="text-slate-300">|</span>
                    <a
                      href="https://wawp.net/terms-of-services/"
                      target="_blank"
                      rel="noreferrer"
                      className="text-slate-500 font-medium text-[11px] h-auto p-0 hover:text-[#004449] no-underline hover:underline transition-all"
                    >
                      Terms
                    </a>
                    <span className="text-slate-300">|</span>
                    <a
                      href="https://wawp.net/privacy-policy/"
                      target="_blank"
                      rel="noreferrer"
                      className="text-slate-500 font-medium text-[11px] h-auto p-0 hover:text-[#004449] no-underline hover:underline transition-all"
                    >
                      Privacy
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <SettingsLayout>
      <SettingsHeader
        title={i18n.subscriptionAccount || "Subscription & Account"}
        description={i18n.subscriptionAccountDesc || `Manage your Wawp account and subscription for ${data.user_email}`}
      >
        <div className="flex items-center gap-3">
          <AnimatePresence mode="wait">
            {saveStatus === 'saving' && (
              <motion.div
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                className="flex items-center gap-2 px-3 py-1.5 bg-indigo-50 text-indigo-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-indigo-100/50"
              >
                <span className="w-1.5 h-1.5 bg-indigo-500 rounded-full animate-pulse" />
                Syncing...
              </motion.div>
            )}
            {saveStatus === 'saved' && (
              <motion.div
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                className="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"
              >
                <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full" />
                Account Synced
              </motion.div>
            )}
            {hasUnsavedChanges && saveStatus === 'idle' && (
              <motion.div
                initial={{ opacity: 0, x: 10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -10 }}
                className="flex items-center gap-2 px-3 py-1.5 bg-amber-50 text-amber-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-amber-100/50"
              >
                <span className="w-1.5 h-1.5 bg-amber-500 rounded-full animate-ping" />
                Unsaved Changes
              </motion.div>
            )}
          </AnimatePresence>

          <SecondaryButton
            onClick={handleRefresh}
            disabled={loading}
            loading={loading}
            icon={loading ? undefined : RefreshCcw}
          >
            {loading ? i18n.refreshing : i18n.btnRefresh}
          </SecondaryButton>
          <SecondaryButton
            onClick={() => window.location.href = data.logout_url}
            icon={LogOut}
          >
            {i18n.btnDisconnect}
          </SecondaryButton>
        </div>
      </SettingsHeader>

      {data.domain_status === 'overload' && <OverloadAlert i18n={i18n} />}
      {data.domain_status === 'not active' && <NotActiveAlert i18n={i18n} />}
      {(data.banned_msg || data.domain_status === 'blocked') && <BlockedAlert i18n={i18n} />}

      {data.is_free_user && data.domain_status !== 'blocked' ? (
        <div className="space-y-6 animate-in slide-in-from-bottom duration-500">
          <SettingCard className="p-0 overflow-hidden">
            <ModernCardHeader
              icon={Sparkles}
              title={i18n.activePlan || 'Active Plan'}
              description={i18n.upgradeSubtitle || 'Monitor your subscription status and domain license.'}
              rightAction={<Badge className="bg-emerald-50 text-emerald-700 border-none px-3 py-1 text-[10px] font-bold uppercase tracking-widest">{i18n.activePlan}: {data.plan_name}</Badge>}
            />
            <CardContent className="relative p-6 md:p-8 pt-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div className="bg-gray-50/50 border border-gray-100 p-5 rounded-2xl">
                  <div className="bg-indigo-50 w-10 h-10 rounded-lg flex items-center justify-center mb-4">
                    <Zap className="w-5 h-5 text-indigo-600" />
                  </div>
                  <h4 className="font-bold text-gray-900 mb-1 uppercase tracking-wider text-xs">{i18n.featUnlimited || 'Unlimited Messages'}</h4>
                  <p className="text-gray-500 text-xs leading-relaxed">Send thousands of messages without monthly limits slowing you down.</p>
                </div>
                <div className="bg-gray-50/50 border border-gray-100 p-5 rounded-2xl">
                  <div className="bg-emerald-50 w-10 h-10 rounded-lg flex items-center justify-center mb-4">
                    <ShieldCheck className="w-5 h-5 text-emerald-600" />
                  </div>
                  <h4 className="font-bold text-gray-900 mb-1 uppercase tracking-wider text-xs">{i18n.featPriority || 'Priority Resources'}</h4>
                  <p className="text-gray-500 text-xs leading-relaxed">Get faster server response times and dedicated automation power.</p>
                </div>
                <div className="bg-gray-50/50 border border-gray-100 p-5 rounded-2xl">
                  <div className="bg-amber-50 w-10 h-10 rounded-lg flex items-center justify-center mb-4">
                    <Star className="w-5 h-5 text-amber-600" />
                  </div>
                  <h4 className="font-bold text-gray-900 mb-1 uppercase tracking-wider text-xs">{i18n.featSupport || 'VIP Remote Support'}</h4>
                  <p className="text-gray-500 text-xs leading-relaxed">Direct access to our expert team for setup and troubleshooting.</p>
                </div>
              </div>

              <div className="flex flex-col sm:flex-row items-center gap-4">
              </div>
            </CardContent>
          </SettingCard>

        </div>
      ) : (data.domain_status !== 'overload' && data.domain_status !== 'blocked') && (
        <div className="space-y-8 animate-in fade-in duration-700">
          <div className="grid grid-cols-1 gap-6">
            <SettingCard className="p-0 overflow-hidden">
              <ModernCardHeader
                icon={Crown}
                title={i18n.activePlan}
                description="Monitor your subscription status and domain license."
              />
              <CardContent className="p-5 flex flex-col gap-6">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Subscription & Account</div>
                    <div className="text-xl font-bold text-gray-900 capitalize tracking-tight">
                      {data.plan_name ? data.plan_name.replace(/\(?lifetime\)?/gi, '').replace(/\(\s*\)/g, '').trim() || data.plan_name : 'Free Plan'}
                    </div>
                  </div>
                  {data.is_lifetime && <Badge className="bg-gray-900 text-white border-none shadow-none text-[10px] px-2 uppercase">{i18n.lifetime}</Badge>}
                </div>

                <div className="space-y-1">
                  <div className="flex flex-row items-center justify-between py-2 border-t border-gray-50">
                    <span className="text-[12px] font-medium text-gray-500 flex items-center gap-2"><Globe className="w-3.5 h-3.5" />{i18n.siteDomain}</span>
                    <span className="text-[12px] font-bold text-gray-900">{window.location.hostname}</span>
                  </div>
                  <div className="flex flex-row items-center justify-between py-2 border-t border-gray-50">
                    <span className="text-[12px] font-medium text-gray-500 flex items-center gap-2"><Shield className="w-3.5 h-3.5" />{i18n.domainStatus}</span>
                    <Badge variant="secondary" className={`border-none shadow-none px-2 py-0.5 text-[10px] uppercase font-bold 
                        ${data.domain_status === 'active' ? 'bg-emerald-50 text-emerald-700' :
                        data.domain_status === 'overload' ? 'bg-amber-50 text-amber-700' :
                          'bg-gray-100 text-gray-600'}`}>
                      {data.domain_status === 'active' ? i18n.active :
                        data.domain_status === 'overload' ? (i18n.overload || 'Overload') :
                          i18n.inactive}
                    </Badge>
                  </div>
                </div>

                {data.subscriptions && data.subscriptions.length > 0 && (
                  <div className="border-t border-gray-50 pt-4">
                    <div className="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-3 flex items-center gap-1.5">
                      <Clock className="w-3.5 h-3.5" />
                      {i18n.nextBillDate}
                    </div>
                    <div className="space-y-2">
                      {data.subscriptions
                        .filter(sub => sub.plan_name)
                        .map((sub, i: number) => (
                          <div key={i} className="flex justify-between items-center text-sm bg-gray-50/50 p-2 rounded-lg border border-gray-100">
                            <span className="text-[12px] font-semibold text-gray-700">{sub.plan_name}</span>
                            <span className="text-[12px] font-bold text-gray-900">{sub.next_bill_date}</span>
                          </div>
                        ))}
                    </div>
                  </div>
                )}

                <div className="border-t border-gray-50 pt-6">
                  <div className="rounded-lg border border-gray-100 overflow-hidden bg-gray-50/30">
                    <ModernCardHeader
                      icon={Activity}
                      title="Share Diagnostic Data"
                      description="Help us improve by sharing non-sensitive system diagnostics."
                      className="border-none bg-transparent !px-5 !pt-5 !pb-4"
                      rightAction={
                        <Switch
                          checked={shareDiagnostics}
                          onCheckedChange={handleToggleDiagnostics}
                        />
                      }
                    />
                  </div>
                </div>

              </CardContent>
              <CardFooter className="p-5 pt-0 mt-auto flex justify-end">
              </CardFooter>
            </SettingCard>
          </div>
        </div>
      )}

    </SettingsLayout>
  );
};

export default Connector;
