"use client";

import { useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import { logger } from "@/core/logger";
import { useInternetConfigure } from "@/features/services/hooks/useInternetConfigure";
import { useInternetEligibility } from "@/features/services/hooks/useInternetEligibility";
import { useServicesBasePath } from "@/features/services/hooks/useServicesBasePath";
import { InternetConfigureView as InternetConfigureInnerView } from "@/features/services/components/internet/InternetConfigureView";
import { Spinner } from "@/components/atoms";

export function InternetConfigureContainer() {
  const router = useRouter();
  const pathname = usePathname();
  const servicesBasePath = useServicesBasePath();
  const eligibilityQuery = useInternetEligibility();
  const vm = useInternetConfigure();

  // Keep /internet/configure strictly in the post-eligibility path.
  useEffect(() => {
    if (!pathname.startsWith("/account")) return;
    if (!eligibilityQuery.isSuccess) return;
    if (eligibilityQuery.data.status === "eligible") return;
    router.replace(`${servicesBasePath}/internet`);
  }, [
    eligibilityQuery.data?.status,
    eligibilityQuery.isSuccess,
    pathname,
    router,
    servicesBasePath,
  ]);

  if (pathname.startsWith("/account")) {
    if (eligibilityQuery.isLoading) {
      return (
        <div className="max-w-2xl mx-auto py-12">
          <div className="bg-card rounded-xl border border-border p-8 shadow-[var(--cp-shadow-1)] text-center">
            <Spinner className="mx-auto mb-4" />
            <p className="text-sm text-muted-foreground">Checking availability…</p>
          </div>
        </div>
      );
    }

    if (eligibilityQuery.isSuccess && eligibilityQuery.data.status !== "eligible") {
      return (
        <div className="max-w-2xl mx-auto py-12">
          <div className="bg-card rounded-xl border border-border p-8 shadow-[var(--cp-shadow-1)] text-center">
            <Spinner className="mx-auto mb-4" />
            <p className="text-sm text-muted-foreground">Redirecting…</p>
          </div>
        </div>
      );
    }
  }

  // Debug: log current state
  logger.debug("InternetConfigure state", {
    plan: vm.plan?.sku,
    mode: vm.mode,
    installation: vm.selectedInstallation?.sku,
    addons: vm.selectedAddonSkus,
  });

  const handleConfirm = () => {
    logger.debug("handleConfirm called, current state", {
      plan: vm.plan?.sku,
      mode: vm.mode,
      installation: vm.selectedInstallation?.sku,
      selectedInstallationSku: vm.selectedInstallation?.sku,
    });

    const params = vm.buildCheckoutSearchParams();
    if (!params) {
      logger.error("Cannot proceed to checkout: missing required configuration", {
        plan: vm.plan?.sku,
        mode: vm.mode,
        installation: vm.selectedInstallation?.sku,
      });

      // Determine what's missing
      const missingItems: string[] = [];
      if (!vm.plan) missingItems.push("plan selection");
      if (!vm.mode) missingItems.push("access mode");
      if (!vm.selectedInstallation) missingItems.push("installation option");

      alert(`Please complete the following before proceeding:\n- ${missingItems.join("\n- ")}`);
      return;
    }

    logger.debug("Navigating to checkout with params", {
      params: params.toString(),
    });
    const orderBasePath = pathname.startsWith("/account") ? "/account/order" : "/order";
    router.push(`${orderBasePath}?${params.toString()}`);
  };

  return <InternetConfigureInnerView {...vm} onConfirm={handleConfirm} />;
}

export default InternetConfigureContainer;
