import { useState, useEffect } from 'react'
import type { DashboardData } from './types'
import {
  Dialog,
  DialogContent,
} from "./components/ui/dialog"
import { 
  CheckCircle2, 
  ArrowRight, 
  ArrowLeft, 
  RefreshCw, 
  ShieldCheck, 
  Wrench, 
  Users, 
  Info,
  Loader2,
  X,
  Sparkles,
  MessageSquare,
  Activity,
  Cable,
  Zap,
  Mail,
  UserPlus,
  Key,
  Globe,
  Smartphone,
  Bell,
  FileCode
} from "lucide-react"
import { toast } from "sonner"
import { motion, AnimatePresence } from "framer-motion"
import {
  ModernCardHeader,
  PrimaryButton,
  OutlineButton
} from './components/ui/settings-ui';
import "./types"

export default function SetupWizard({ data: dashboardData }: { data?: DashboardData }) {
  const [isOpen, setIsOpen] = useState(false)
  const [step, setStep] = useState(1)
  const [loading, setLoading] = useState(false)
  const [finalChecks, setFinalChecks] = useState<{
    db_ok: boolean;
    cron_ok: boolean;
    cron_const_ok: boolean;
    instances_ok: boolean;
    wp_cron_enabled: boolean;
  } | null>(null)
  const [runningChecks, setRunningChecks] = useState(false)

  const rawData = dashboardData || window.wawpDashboardData
  const data = rawData?.wizardData
  const initialStep = rawData?.global?.popupStep || 0
  const rtl = rawData?.rtl || false;

  useEffect(() => {
    if (initialStep > 0) {
      setStep(initialStep)
      setIsOpen(true)
    }
  }, [initialStep])

  if (!data) return null

  const totalSteps = 4
  const progress = (step / totalSteps) * 100

  const handleNext = () => {
    if (step < totalSteps) {
      setStep(step + 1)
      if (step + 1 === 4) {
        runFinalChecks()
      }
    } else {
      setIsOpen(false)
    }
  }

  const handlePrev = () => {
    if (step > 1) {
      setStep(step - 1)
    }
  }

  const runSync = async () => {
    setLoading(true)
    try {
      const response = await fetch(`${rawData?.global?.apiRestUrl}/system/sync-users`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': rawData?.global?.wpRestNonce
        }
      })
      const result = await response.json()
      if (result.success) {
        toast.success("Users synchronized successfully")
      } else {
        toast.error(result.data || "Failed to sync users")
      }
    } catch {
      toast.error("An error occurred during sync")
    } finally {
      setLoading(false)
    }
  }

  const runRepair = async () => {
    setLoading(true)
    try {
      const response = await fetch(`${rawData?.global?.apiRestUrl}/system/repair`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': rawData?.global?.wpRestNonce
        }
      })
      const result = await response.json()
      if (result.success) {
        toast.success("All issues repaired successfully")
      } else {
        toast.error(result.data || "Failed to repair issues")
      }
    } catch {
      toast.error("An error occurred during repair")
    } finally {
      setLoading(false)
    }
  }

  const runFinalChecks = async () => {
    setRunningChecks(true)
    setFinalChecks(null)
    try {
      const response = await fetch(`${rawData?.global?.apiRestUrl}/system/wizard-checks`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': rawData?.global?.wpRestNonce
        }
      })
      const result = await response.json()
      if (result.success) {
        setFinalChecks(result.data)
      }
    } catch {
      if (step === 4) toast.error("Failed to run final checks")
    } finally {
      setRunningChecks(false)
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogContent className="sm:max-w-[1140px] p-0 overflow-hidden border-none bg-white rounded-[5px] shadow-2xl" showCloseButton={false}>
        <div className="flex flex-col min-h-[600px]" dir={rtl ? 'rtl' : 'ltr'}>
          
          <AnimatePresence mode="wait">
            <motion.div
              key={step}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              transition={{ duration: 0.2 }}
              className="flex-grow flex flex-col"
            >
              {step === 1 && (
                <div className="flex flex-col md:flex-row flex-grow">
                  {/* Left: Features (Like Connector) */}
                  <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: (rawData.global?.pluginUrl || '') + "assets/img/senders/whatsapp.svg", color: 'text-emerald-500', desc: 'Direct message dispatch' },
                          { label: 'Email SMTP & Templates', icon: Mail, iconPath: (rawData.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: Key, 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 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>

                  {/* Right: Connect (Like Connector) */}
                  <div className="flex-1 flex flex-col bg-white overflow-hidden relative">
                    <button 
                      onClick={() => setIsOpen(false)}
                      className="absolute top-4 right-4 z-20 w-8 h-8 flex items-center justify-center rounded-full bg-white border border-slate-100 text-slate-400 hover:text-rose-500 transition-colors shadow-sm"
                    >
                      <X size={14} />
                    </button>

                    <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-6 relative">
                        {data.isSso ? (
                          <PrimaryButton className="w-full h-14 rounded-xl font-bold uppercase tracking-widest text-[11px]" onClick={handleNext}>
                            Continue Setup
                            <ArrowRight className="w-4 h-4 ml-2" />
                          </PrimaryButton>
                        ) : (
                          <a 
                            href={rawData.connector?.login_url || data.loginUrl} 
                            className="w-full h-14 rounded-xl bg-[#004449] hover:bg-[#003337] !text-white shadow-none font-bold uppercase tracking-widest text-[11px] group active:scale-[0.98] flex items-center justify-center gap-2 no-underline transition-all"
                          >
                            Authenticate Now
                            <ArrowRight className={`w-4 h-4 transition-transform group-hover:translate-x-1 ${rtl ? 'rotate-180 group-hover:-translate-x-1' : ''}`} />
                          </a>
                        )}
                        
                        {!data.isSso && (
                          <div className="pt-8 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>
              )}

              {step > 1 && (
                <div className="flex flex-col flex-grow">
                  <ModernCardHeader 
                    icon={step === 2 ? ShieldCheck : step === 3 ? Activity : Sparkles}
                    title={step === 2 ? "Account Linked" : step === 3 ? "Sync & Health" : "Ready to Go"}
                    description={step === 2 ? "Your Wawp account is successfully connected." : step === 3 ? "Ensure your system is performing optimally." : "Wawp is fully configured and ready to use."}
                    rightAction={
                      <div className="flex items-center gap-4">
                        <div className="h-1.5 w-32 bg-slate-100 rounded-full overflow-hidden shrink-0">
                          <div className="h-full bg-[#004449] transition-all duration-500" style={{ width: `${progress}%` }} />
                        </div>
                        <button 
                          onClick={() => setIsOpen(false)}
                          className="w-8 h-8 flex items-center justify-center rounded-full bg-white border border-slate-200 text-slate-400 hover:text-rose-500 transition-colors"
                        >
                          <X size={14} />
                        </button>
                      </div>
                    }
                  />

                  <div className="flex-grow p-10 lg:p-12">
                    {step === 2 && (
                      <div className="flex flex-col items-center justify-center py-8 gap-8">
                        <div className="flex items-center gap-16 relative">
                           <div className="w-20 h-20 bg-white rounded-[1.5rem] shadow-sm flex items-center justify-center border border-slate-100">
                              <img src="/wp-content/plugins/automation-web-platform/assets/img/wawp.webp" className="w-12 h-12 object-contain" />
                           </div>
                           <div className="absolute left-1/2 -translate-x-1/2 flex items-center justify-center w-full">
                              <div className="h-[2px] w-24 border-t-2 border-dashed border-slate-200" />
                              <div className="absolute w-8 h-8 rounded-full bg-emerald-500 flex items-center justify-center text-white border-4 border-white shadow-sm">
                                <CheckCircle2 className="w-4 h-4" />
                              </div>
                           </div>
                           <div className="w-20 h-20 bg-white rounded-[1.5rem] shadow-sm flex items-center justify-center border border-slate-100 overflow-hidden p-0.5">
                              <img src="/wp-content/plugins/automation-web-platform/assets/img/user.webp" className="w-full h-full object-cover rounded-[1.4rem]" />
                           </div>
                        </div>
                        <div className="text-center max-w-sm">
                          <div className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-2">Authenticated Account</div>
                          <div className="text-lg font-bold text-slate-900 mb-1">{data.ssoEmail}</div>
                          <button onClick={() => window.location.href = data.disconnectUrl} className="text-[11px] font-bold text-rose-500 hover:text-rose-600 transition-colors uppercase tracking-widest mt-4">
                            Not you? Disconnect Account
                          </button>
                        </div>
                      </div>
                    )}

                    {step === 3 && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 py-4">
                        <div className="p-6 bg-slate-50/50 rounded-2xl border border-slate-100 flex flex-col items-center text-center">
                          <div className="w-12 h-12 bg-white rounded-xl flex items-center justify-center border border-slate-100 mb-6 group">
                            <Users className="w-5 h-5 text-blue-500 transition-transform group-hover:scale-110" />
                          </div>
                           <div className="mb-6">
                            <h4 className="font-bold text-slate-900 mb-1">User Synchronization</h4>
                            <p className="text-xs font-medium text-slate-500 leading-relaxed">Ensure all users are synced for OTP and notifications.</p>
                          </div>
                          <PrimaryButton className="w-full h-11 border-slate-200" onClick={runSync} loading={loading}>
                            <RefreshCw className="w-4 h-4 mr-2" />
                            Synchronize Users
                          </PrimaryButton>
                        </div>

                        <div className="p-6 bg-slate-50/50 rounded-2xl border border-slate-100 flex flex-col items-center text-center">
                          <div className={`w-12 h-12 bg-white rounded-xl flex items-center justify-center border border-slate-100 mb-6 group ${data.totalIssues > 0 ? 'text-amber-500' : 'text-emerald-500'}`}>
                            {data.totalIssues > 0 ? <Wrench className="w-5 h-5 transition-transform group-hover:rotate-12" /> : <ShieldCheck className="w-5 h-5" />}
                          </div>
                          <div className="mb-6">
                            <h4 className="font-bold text-slate-900 mb-1">System Health</h4>
                            <p className={`text-xs font-black uppercase tracking-widest mt-2 ${data.totalIssues > 0 ? 'text-amber-500' : 'text-emerald-500'}`}>
                              {data.totalIssues > 0 ? `${data.totalIssues} Optimizations Ready` : 'Site is Optimized'}
                            </p>
                          </div>
                          <div className="flex gap-3 w-full">
                            <OutlineButton className="flex-1 h-11 border-slate-200" onClick={runRepair} loading={loading}>
                              <Wrench className="w-4 h-4 mr-2" />
                              Repair
                            </OutlineButton>
                            <a href="admin.php?page=wawp&wawp_section=system_info" target="_blank" className="w-11 h-11 bg-white border border-slate-200 rounded-lg flex items-center justify-center text-slate-400 hover:text-indigo-600 transition-all">
                              <Info className="w-4 h-4" />
                            </a>
                          </div>
                        </div>
                      </div>
                    )}

                    {step === 4 && (
                      <div className="flex flex-col items-center justify-center py-6 min-h-[300px]">
                        {!finalChecks || runningChecks ? (
                          <div className="flex flex-col items-center">
                            <Loader2 className="w-12 h-12 text-[#004449] animate-spin mb-6" />
                            <h2 className="text-xl font-bold text-slate-900 mb-2">Finalizing Site Setup...</h2>
                            <p className="text-sm font-medium text-slate-400">Verifying database and cloud sync...</p>
                          </div>
                        ) : (
                          <div className="w-full flex flex-col items-center">
                            <div className="w-20 h-20 bg-emerald-50 rounded-[1.8rem] flex items-center justify-center mb-8 border border-emerald-100/50">
                              <CheckCircle2 className="w-10 h-10 text-emerald-600" />
                            </div>
                            <h2 className="text-2xl font-bold text-slate-900 mb-2">Everything is Ready!</h2>
                            <p className="text-sm font-medium text-slate-500 mb-10">Wawp is now active and monitoring your site.</p>
                            
                            <div className="grid grid-cols-2 gap-4 w-full max-w-sm mb-12">
                               <div className="p-4 bg-slate-50 border border-slate-100 rounded-2xl flex flex-col items-center">
                                  <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Database</span>
                                  <span className={`text-xs font-bold ${finalChecks.db_ok ? 'text-emerald-600' : 'text-amber-600'}`}>
                                    {finalChecks.db_ok ? 'CONNECTED' : 'ISSUES'}
                                  </span>
                               </div>
                               <div className="p-4 bg-slate-50 border border-slate-100 rounded-2xl flex flex-col items-center">
                                  <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">Instances</span>
                                  <span className={`text-xs font-bold ${finalChecks.instances_ok ? 'text-emerald-600' : 'text-amber-600'}`}>
                                    {finalChecks.instances_ok ? 'STABLE' : 'OFFLINE'}
                                  </span>
                               </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    <div className="mt-auto flex justify-between pt-8">
                      <button 
                        onClick={handlePrev} 
                        className={`flex items-center gap-2 text-[11px] font-black uppercase tracking-[0.2em] text-slate-400 hover:text-slate-600 transition-colors ${step === 1 ? 'invisible' : ''}`}
                      >
                        <ArrowLeft size={16} /> Previous
                      </button>
                      
                      {step === 4 ? (
                        <a 
                          href="admin.php?page=wawp&wawp_section=dashboard"
                          className="h-12 px-10 bg-[#004449] hover:bg-[#003337] !text-white rounded-xl font-bold uppercase tracking-widest text-[11px] flex items-center justify-center transition-all shadow-none"
                        >
                          Go to Dashboard
                        </a>
                      ) : (
                        <PrimaryButton 
                          onClick={handleNext} 
                          className="h-12 px-10 font-bold uppercase tracking-widest text-[11px] rounded-xl"
                          disabled={step === 1 && !data.isSso}
                        >
                          Next Step <ArrowRight size={16} className="ml-2" />
                        </PrimaryButton>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </motion.div>
          </AnimatePresence>
        </div>
      </DialogContent>
    </Dialog>
  )
}
