"use client";

import { useEffect, useState, type ReactElement } from "react";
import { PageLayout } from "@/components/templates/PageLayout";
import { ProgressSteps } from "@/components/molecules";
import { Button } from "@/components/atoms/button";
import { CardBadge } from "@/features/catalog/components/base/CardBadge";
import type { BadgeVariant } from "@/features/catalog/components/base/CardBadge";
import { ServerIcon, ArrowLeftIcon } from "@heroicons/react/24/outline";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
  InternetAddonCatalogItem,
} from "@customer-portal/domain/catalog";
import type { AccessModeValue } from "@customer-portal/domain/orders";
import { ConfigureLoadingSkeleton } from "./components/ConfigureLoadingSkeleton";
import { ServiceConfigurationStep } from "./steps/ServiceConfigurationStep";
import { InstallationStep } from "./steps/InstallationStep";
import { AddonsStep } from "./steps/AddonsStep";
import { ReviewOrderStep } from "./steps/ReviewOrderStep";
import { useConfigureState } from "./hooks/useConfigureState";
import { parsePlanName } from "@/features/catalog/components/internet/utils/planName";

interface Props {
  plan: InternetPlanCatalogItem | null;
  loading: boolean;
  addons: InternetAddonCatalogItem[];
  installations: InternetInstallationCatalogItem[];
  onConfirm: () => void;
  // State from parent hook
  mode: AccessModeValue | null;
  setMode: (mode: AccessModeValue) => void;
  selectedInstallation: InternetInstallationCatalogItem | null;
  setSelectedInstallationSku: (sku: string | null) => void;
  selectedAddonSkus: string[];
  setSelectedAddonSkus: (skus: string[]) => void;
  currentStep: number;
  setCurrentStep: (step: number) => void;
}

const STEPS = [
  { number: 1, title: "Configuration", description: "Service setup" },
  { number: 2, title: "Installation", description: "Installation method" },
  { number: 3, title: "Add-ons", description: "Optional services" },
  { number: 4, title: "Review", description: "Order summary" },
] as const;

export function InternetConfigureContainer({
  plan,
  loading,
  addons,
  installations,
  onConfirm,
  mode,
  setMode,
  selectedInstallation,
  setSelectedInstallationSku,
  selectedAddonSkus,
  setSelectedAddonSkus,
  currentStep,
  setCurrentStep,
}: Props) {
  const [renderedStep, setRenderedStep] = useState(currentStep);
  const [transitionPhase, setTransitionPhase] = useState<"idle" | "enter" | "exit">("idle");
  // Use local state ONLY for step validation, step management now in Zustand
  const { canProceedFromStep } = useConfigureState(
    plan,
    installations,
    addons,
    mode,
    selectedInstallation,
    currentStep,
    setCurrentStep
  );

  const handleAddonSelection = (newSelectedSkus: string[]) => setSelectedAddonSkus(newSelectedSkus);

  const progressSteps = STEPS.map(step => ({
    ...step,
    completed: currentStep > step.number,
  }));

  useEffect(() => {
    if (currentStep === renderedStep) return;
    setTransitionPhase("exit");
    const exitTimer = window.setTimeout(() => {
      setRenderedStep(currentStep);
      setTransitionPhase("enter");
    }, 100);

    return () => {
      window.clearTimeout(exitTimer);
    };
  }, [currentStep, renderedStep]);

  useEffect(() => {
    if (transitionPhase !== "enter") return;
    const enterTimer = window.setTimeout(() => {
      setTransitionPhase("idle");
    }, 150);

    return () => {
      window.clearTimeout(enterTimer);
    };
  }, [transitionPhase]);

  if (loading) {
    return <ConfigureLoadingSkeleton />;
  }

  if (!plan) {
    return (
      <PageLayout
        icon={<ServerIcon />}
        title="Configure Internet Service"
        description="Set up your internet service options"
      >
        <div className="text-center py-12">
          <p className="text-gray-500">Plan not found</p>
        </div>
      </PageLayout>
    );
  }

  const isTransitioning = transitionPhase !== "idle";

  let stepContent: ReactElement | null = null;
  switch (renderedStep) {
    case 1:
      stepContent = (
        <ServiceConfigurationStep
          plan={plan}
          mode={mode}
          setMode={setMode}
          isTransitioning={isTransitioning}
          onNext={() => canProceedFromStep(1) && setCurrentStep(2)}
        />
      );
      break;
    case 2:
      stepContent = (
        <InstallationStep
          installations={installations}
          selectedInstallation={selectedInstallation}
          setSelectedInstallationSku={setSelectedInstallationSku}
          isTransitioning={isTransitioning}
          onBack={() => setCurrentStep(1)}
          onNext={() => canProceedFromStep(2) && setCurrentStep(3)}
        />
      );
      break;
    case 3:
      stepContent = selectedInstallation ? (
        <AddonsStep
          addons={addons}
          selectedAddonSkus={selectedAddonSkus}
          onAddonToggle={handleAddonSelection}
          isTransitioning={isTransitioning}
          onBack={() => setCurrentStep(2)}
          onNext={() => setCurrentStep(4)}
        />
      ) : (
        <InstallationStep
          installations={installations}
          selectedInstallation={selectedInstallation}
          setSelectedInstallationSku={setSelectedInstallationSku}
          isTransitioning={isTransitioning}
          onBack={() => setCurrentStep(1)}
          onNext={() => canProceedFromStep(2) && setCurrentStep(3)}
        />
      );
      break;
    case 4:
      stepContent = selectedInstallation ? (
        <ReviewOrderStep
          plan={plan}
          selectedInstallation={selectedInstallation}
          selectedAddonSkus={selectedAddonSkus}
          addons={addons}
          mode={mode}
          isTransitioning={isTransitioning}
          onBack={() => setCurrentStep(3)}
          onConfirm={onConfirm}
        />
      ) : (
        <ServiceConfigurationStep
          plan={plan}
          mode={mode}
          setMode={setMode}
          isTransitioning={isTransitioning}
          onNext={() => canProceedFromStep(1) && setCurrentStep(2)}
        />
      );
      break;
    default:
      stepContent = (
        <ServiceConfigurationStep
          plan={plan}
          mode={mode}
          setMode={setMode}
          isTransitioning={isTransitioning}
          onNext={() => canProceedFromStep(1) && setCurrentStep(2)}
        />
      );
  }

  return (
    <PageLayout
      icon={<ServerIcon />}
      title="Configure Internet Service"
      description="Set up your internet service options"
    >
      <div className="min-h-[70vh] bg-gradient-to-br from-slate-50 via-blue-50/20 to-slate-50">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* Plan Header */}
          <PlanHeader plan={plan} />

          {/* Progress Steps */}
          <div className="mb-10">
            <ProgressSteps steps={progressSteps} currentStep={currentStep} />
          </div>

          {/* Step Content */}
          <div className="space-y-8" key={renderedStep}>
            {stepContent}
          </div>
        </div>
      </div>
    </PageLayout>
  );
}

function PlanHeader({ plan }: { plan: InternetPlanCatalogItem }) {
  const { baseName: planBaseName, detail: planDetail } = parsePlanName(plan);

  return (
    <div className="text-center mb-8 animate-in fade-in duration-300">
      <Button
        as="a"
        href="/catalog/internet"
        variant="outline"
        size="sm"
        leftIcon={<ArrowLeftIcon className="w-4 h-4" />}
        className="mb-6"
      >
        Back to Internet Plans
      </Button>

      <h1 className="text-2xl md:text-3xl font-bold text-gray-900 mb-5">Configure your plan</h1>
      <span className="sr-only">
        {planBaseName}
        {planDetail ? ` (${planDetail})` : ""}
      </span>

      <div className="inline-flex flex-wrap items-center justify-center gap-3 bg-white px-6 py-3 rounded-full border border-blue-100 shadow-sm text-sm">
        {plan.internetPlanTier ? (
          <CardBadge
            text={plan.internetPlanTier}
            variant={getTierBadgeVariant(plan.internetPlanTier)}
            size="sm"
          />
        ) : null}
        {planDetail ? <CardBadge text={planDetail} variant="family" size="sm" /> : null}
        {plan.monthlyPrice && plan.monthlyPrice > 0 ? (
          <span className="inline-flex items-center rounded-full bg-blue-600/10 px-3 py-1 text-sm font-semibold text-blue-700">
            ¥{plan.monthlyPrice.toLocaleString()}/month
          </span>
        ) : null}
      </div>
    </div>
  );
}

function getTierBadgeVariant(tier?: string | null): BadgeVariant {
  switch (tier) {
    case "Gold":
      return "gold";
    case "Platinum":
      return "platinum";
    case "Silver":
      return "silver";
    case "Recommended":
      return "recommended";
    default:
      return "default";
  }
}
