"use client";

import { useEffect, useState, type ReactElement } from "react";
import { PageLayout } from "@/components/templates/PageLayout";
import { ProgressSteps } from "@/components/molecules";
import { ServerIcon } from "@heroicons/react/24/outline";
import type {
  InternetPlanCatalogItem,
  InternetInstallationCatalogItem,
  InternetAddonCatalogItem,
} from "@customer-portal/domain/services";
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 { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { PlanHeader } from "@/features/services/components/internet/PlanHeader";

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;

function resolveStepContent({
  renderedStep,
  plan,
  mode,
  setMode,
  isTransitioning,
  canProceedFromStep,
  setCurrentStep,
  installations,
  selectedInstallation,
  setSelectedInstallationSku,
  addons,
  selectedAddonSkus,
  handleAddonSelection,
  onConfirm,
}: {
  renderedStep: number;
  plan: NonNullable<Props["plan"]>;
  mode: Props["mode"];
  setMode: Props["setMode"];
  isTransitioning: boolean;
  canProceedFromStep: (step: number) => boolean;
  setCurrentStep: (step: number) => void;
  installations: Props["installations"];
  selectedInstallation: Props["selectedInstallation"];
  setSelectedInstallationSku: Props["setSelectedInstallationSku"];
  addons: Props["addons"];
  selectedAddonSkus: Props["selectedAddonSkus"];
  handleAddonSelection: (skus: string[]) => void;
  onConfirm: Props["onConfirm"];
}): ReactElement {
  const configStep = (
    <ServiceConfigurationStep
      plan={plan}
      mode={mode}
      setMode={setMode}
      isTransitioning={isTransitioning}
      onNext={() => canProceedFromStep(1) && setCurrentStep(2)}
    />
  );
  const installStep = (
    <InstallationStep
      installations={installations}
      selectedInstallation={selectedInstallation}
      setSelectedInstallationSku={setSelectedInstallationSku}
      isTransitioning={isTransitioning}
      onBack={() => setCurrentStep(1)}
      onNext={() => canProceedFromStep(2) && setCurrentStep(3)}
    />
  );

  switch (renderedStep) {
    case 1:
      return configStep;
    case 2:
      return installStep;
    case 3:
      if (!selectedInstallation) return installStep;
      return (
        <AddonsStep
          addons={addons}
          selectedAddonSkus={selectedAddonSkus}
          onAddonToggle={handleAddonSelection}
          isTransitioning={isTransitioning}
          onBack={() => setCurrentStep(2)}
          onNext={() => setCurrentStep(4)}
        />
      );
    case 4:
      if (!selectedInstallation) return configStep;
      return (
        <ReviewOrderStep
          plan={plan}
          selectedInstallation={selectedInstallation}
          selectedAddonSkus={selectedAddonSkus}
          addons={addons}
          mode={mode}
          isTransitioning={isTransitioning}
          onBack={() => setCurrentStep(3)}
          onConfirm={onConfirm}
        />
      );
    default:
      return configStep;
  }
}

export function InternetConfigureContainer({
  plan,
  loading,
  addons,
  installations,
  onConfirm,
  mode,
  setMode,
  selectedInstallation,
  setSelectedInstallationSku,
  selectedAddonSkus,
  setSelectedAddonSkus,
  currentStep,
  setCurrentStep,
}: Props) {
  const servicesBasePath = useServicesBasePath();
  const [renderedStep, setRenderedStep] = useState(currentStep);
  const [transitionPhase, setTransitionPhase] = useState<"idle" | "enter" | "exit">("idle");
  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"
        backLink={{ label: "Back to Services", href: "/account/services" }}
      >
        <div className="text-center py-12">
          <p className="text-muted-foreground">Plan not found</p>
        </div>
      </PageLayout>
    );
  }

  const stepContent = resolveStepContent({
    renderedStep,
    plan,
    mode,
    setMode,
    isTransitioning: transitionPhase !== "idle",
    canProceedFromStep,
    setCurrentStep,
    installations,
    selectedInstallation,
    setSelectedInstallationSku,
    addons,
    selectedAddonSkus,
    handleAddonSelection,
    onConfirm,
  });

  return (
    <PageLayout
      icon={<ServerIcon />}
      title="Configure Internet Service"
      backLink={{ label: "Back to Services", href: "/account/services" }}
    >
      <div className="min-h-[70vh]">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <PlanHeader
            plan={plan}
            backHref={`${servicesBasePath}/internet`}
            backLabel="Back to Internet Plans"
          />
          <div className="mb-10">
            <ProgressSteps steps={progressSteps} currentStep={currentStep} />
          </div>
          <div className="space-y-8" key={renderedStep}>
            {stepContent}
          </div>
        </div>
      </div>
    </PageLayout>
  );
}
