/**
 * Onboarding Wizard - Main onboarding flow container
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { CheckCircle2, Circle } from "lucide-react";
import type { Lang } from "@/lib/config";
import type {
  OnboardingStepId,
  OnboardingProgress,
  OnboardingStatus,
  VoiceAgentConfig,
  WhatsAppMethod,
} from "@/lib/types/onboarding.types";
import {
  getStepDisplayName,
  getStepNumber,
} from "@/lib/types/onboarding.types";

// Import step components
import WelcomeStep from "./steps/WelcomeStep";
import WhatsAppSetupStep from "./steps/WhatsAppSetupStep";
import VoiceAgentSetupStep from "./steps/VoiceAgentSetupStep";
import KnowledgeBaseSetupStep from "./steps/KnowledgeBaseSetupStep";
import WorkflowActivationStep from "./steps/WorkflowActivationStep";
import TestingStep from "./steps/TestingStep";

interface OnboardingWizardProps {
  lang: Lang;
  initialProgress: OnboardingProgress;
  initialStatus: OnboardingStatus;
  packageTier: string;
}

export default function OnboardingWizard({
  lang,
  initialProgress,
  initialStatus,
  packageTier,
}: OnboardingWizardProps) {
  const router = useRouter();
  const isAr = lang === "ar";
  const [currentStep, setCurrentStep] = useState<OnboardingStepId>(
    initialStatus.currentStep,
  );
  const [progress, setProgress] = useState(initialProgress);
  const [status, setStatus] = useState(initialStatus);
  const [updating, setUpdating] = useState(false);

  const t = {
    progressLabel: isAr ? "التقدم" : "Progress",
    stepOf: isAr ? "الخطوة {current} من {total}" : "Step {current} of {total}",
    completing: isAr ? "جارٍ إكمال الإعداد..." : "Completing setup...",
  };

  // Update progress on server
  const updateProgress = useCallback(
    async (step: OnboardingStepId, completed: boolean = true, data?: any) => {
      setUpdating(true);
      try {
        const response = await fetch("/api/onboarding/progress", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ step, completed, data }),
        });

        if (response.ok) {
          const result = await response.json();
          setProgress(result.progress);
          setStatus(result.status);
        }
      } catch (error) {
        console.error("Error updating progress:", error);
      } finally {
        setUpdating(false);
      }
    },
    [],
  );

  // Mark onboarding as complete
  const completeOnboarding = useCallback(async () => {
    try {
      const response = await fetch("/api/onboarding/complete", {
        method: "POST",
      });

      if (response.ok) {
        // Redirect to dashboard
        router.push(`/${lang}/dashboard?tab=overview`);
      }
    } catch (error) {
      console.error("Error completing onboarding:", error);
    }
  }, [lang, router]);

  // Step navigation handlers
  const goToNextStep = useCallback(
    (nextStepId?: OnboardingStepId) => {
      if (nextStepId) {
        setCurrentStep(nextStepId);
      } else {
        const steps: OnboardingStepId[] = [
          "welcome",
          "whatsapp",
          "voiceAgent",
          "knowledgeBase",
          "workflows",
          "testing",
        ];
        const currentIndex = steps.indexOf(currentStep);
        if (currentIndex < steps.length - 1) {
          setCurrentStep(steps[currentIndex + 1]);
        }
      }
    },
    [currentStep],
  );

  // Step-specific handlers
  const handleWelcomeContinue = async () => {
    await updateProgress("welcome", true);
    goToNextStep("whatsapp");
  };

  const handleWhatsAppContinue = async (method: WhatsAppMethod) => {
    await updateProgress("whatsapp", true, { whatsappMethod: method });
    goToNextStep("voiceAgent");
  };

  const handleWhatsAppSkip = async () => {
    await updateProgress("whatsapp", true, { whatsappMethod: "skipped" });
    goToNextStep("voiceAgent");
  };

  const handleVoiceAgentContinue = async (config: VoiceAgentConfig) => {
    await updateProgress("voiceAgent", true);
    goToNextStep("knowledgeBase");
  };

  const handleKnowledgeBaseContinue = async () => {
    await updateProgress("knowledgeBase", true);
    goToNextStep("workflows");
  };

  const handleKnowledgeBaseSkip = async () => {
    await updateProgress("knowledgeBase", true);
    goToNextStep("workflows");
  };

  const handleWorkflowsContinue = async () => {
    await updateProgress("workflows", true);
    goToNextStep("testing");
  };

  const handleTestingContinue = async () => {
    await updateProgress("testing", true);
    await completeOnboarding();
  };

  // Render current step
  const renderStep = () => {
    switch (currentStep) {
      case "welcome":
        return <WelcomeStep lang={lang} onContinue={handleWelcomeContinue} />;
      case "whatsapp":
        return (
          <WhatsAppSetupStep
            lang={lang}
            onContinue={handleWhatsAppContinue}
            onSkip={handleWhatsAppSkip}
          />
        );
      case "voiceAgent":
        return (
          <VoiceAgentSetupStep
            lang={lang}
            onContinue={handleVoiceAgentContinue}
          />
        );
      case "knowledgeBase":
        return (
          <KnowledgeBaseSetupStep
            lang={lang}
            onContinue={handleKnowledgeBaseContinue}
            onSkip={handleKnowledgeBaseSkip}
          />
        );
      case "workflows":
        return (
          <WorkflowActivationStep
            lang={lang}
            packageTier={packageTier}
            onContinue={handleWorkflowsContinue}
          />
        );
      case "testing":
        return <TestingStep lang={lang} onContinue={handleTestingContinue} />;
      default:
        return null;
    }
  };

  const steps: OnboardingStepId[] = [
    "welcome",
    "whatsapp",
    "voiceAgent",
    "knowledgeBase",
    "workflows",
    "testing",
  ];
  const currentStepNumber = getStepNumber(currentStep);
  const totalSteps = steps.length;

  return (
    <div
      className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100"
      dir={isAr ? "rtl" : "ltr"}
    >
      {/* Ambient Background */}
      <div className="fixed inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-brand-green/10 to-emerald-500/5 rounded-full blur-3xl" />
        <div className="absolute top-1/2 -left-40 w-96 h-96 bg-gradient-to-br from-blue-500/5 to-indigo-500/10 rounded-full blur-3xl" />
      </div>

      {/* Content */}
      <div className="relative z-10 max-w-4xl mx-auto px-4 py-8 sm:px-6 lg:px-8">
        {/* Progress Header */}
        <div className="mb-8">
          {/* Progress Bar */}
          <div className="mb-6">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm font-semibold text-slate-700">
                {t.progressLabel}
              </span>
              <span className="text-sm font-semibold text-brand-green">
                {status.progressPercentage}%
              </span>
            </div>
            <div className="h-2 bg-slate-200 rounded-full overflow-hidden">
              <div
                className="h-full bg-gradient-to-r from-brand-green to-emerald-600 transition-all duration-500 ease-out"
                style={{ width: `${status.progressPercentage}%` }}
              />
            </div>
          </div>

          {/* Step Indicators */}
          <div className="flex items-center justify-between">
            {steps.map((step, index) => {
              const stepNum = index + 1;
              const isActive = step === currentStep;
              const isCompleted = status.completedSteps.includes(step);

              return (
                <div key={step} className="flex flex-col items-center gap-2">
                  <div
                    className={`flex items-center justify-center w-10 h-10 rounded-full border-2 transition-all ${
                      isActive
                        ? "border-brand-green bg-brand-green text-white shadow-lg shadow-brand-green/25"
                        : isCompleted
                          ? "border-brand-green bg-brand-green/10 text-brand-green"
                          : "border-slate-300 bg-white text-slate-400"
                    }`}
                  >
                    {isCompleted ? (
                      <CheckCircle2 className="w-5 h-5" />
                    ) : (
                      <span className="text-sm font-bold">{stepNum}</span>
                    )}
                  </div>
                  <span
                    className={`hidden sm:block text-xs font-medium ${
                      isActive || isCompleted
                        ? "text-slate-900"
                        : "text-slate-400"
                    }`}
                  >
                    {getStepDisplayName(step, lang)}
                  </span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Current Step Number (Mobile) */}
        <div className="sm:hidden mb-6 text-center">
          <span className="text-sm font-medium text-slate-600">
            {t.stepOf
              .replace("{current}", currentStepNumber.toString())
              .replace("{total}", totalSteps.toString())}
          </span>
        </div>

        {/* Step Content */}
        <div className="bg-white/80 backdrop-blur-sm rounded-3xl shadow-xl border border-slate-200/80 p-6 sm:p-8 md:p-10">
          {updating && (
            <div className="absolute inset-0 bg-white/50 backdrop-blur-sm rounded-3xl flex items-center justify-center z-50">
              <div className="text-center">
                <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto mb-3" />
                <p className="text-sm font-medium text-slate-600">
                  {t.completing}
                </p>
              </div>
            </div>
          )}
          {renderStep()}
        </div>

        {/* Footer */}
        <div className="mt-8 text-center">
          <p className="text-sm text-slate-500">
            {isAr ? "بحاجة إلى مساعدة؟" : "Need help?"}{" "}
            <a
              href={`/${lang}/contact`}
              className="font-medium text-brand-green hover:text-brand-greenHover"
            >
              {isAr ? "اتصل بالدعم" : "Contact support"}
            </a>
          </p>
        </div>
      </div>
    </div>
  );
}
